Example usage for org.springframework.context.support ClassPathXmlApplicationContext getBeansOfType

List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext getBeansOfType

Introduction

In this page you can find the example usage for org.springframework.context.support ClassPathXmlApplicationContext getBeansOfType.

Prototype

@Override
    public <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException 

Source Link

Usage

From source file:commonline.query.gui.Frame.java

public static void main(String args[]) throws Exception {
    Plastic3DLookAndFeel.setTabStyle(Plastic3DLookAndFeel.TAB_STYLE_METAL_VALUE);
    UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");

    System.setProperty("com.apple.macos.useScreenMenuBar", "true");

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("MainContext.xml");

    List dataSources = new ArrayList();
    dataSources.addAll(context.getBeansOfType(RecordParserDataSource.class).values());
    CommonlineRecordRepository repository = (CommonlineRecordRepository) context.getBean("clRepository");

    Frame frame = new Frame(System.getProperty("os.name").toLowerCase().indexOf("mac") != -1, dataSources,
            repository);/*from  w  ww.  jav  a 2s  . c  om*/
    frame.setVisible(true);
}

From source file:com.googlecode.deadalus.server.internal.LocalObjectFactoryRegistry.java

public void addJarFile(File jarFile) throws IOException {
    // add the file to the classloader
    if (jarFile.exists())
        System.out.println("jarFile = " + jarFile);
    classLoader.addJarFile(jarFile);//  ww w. j  av  a 2s  . c  o m
    // get the resources
    Resource springCtxResource = new ClassPathResource("META-INF/factories.xml", classLoader);
    // @todo: do we need to reset this at the end?
    Thread.currentThread().setContextClassLoader(classLoader);
    if (springCtxResource.exists()) {
        // create the spring context for the application
        String[] locations = new String[] { "/META-INF/factories.xml" };
        ClassPathXmlApplicationContext springCtx = new ClassPathXmlApplicationContext(locations, parentCtx);
        Map<String, ObjectFactory> factories = springCtx.getBeansOfType(ObjectFactory.class);
        // now register them with the registry
        for (Map.Entry<String, ObjectFactory> factoryEntry : factories.entrySet()) {
            UUID clsId = factoryEntry.getValue().getClassIdentifier();
            // double check if we already had a factory registered for this UUID
            if (!registry.containsKey(clsId)) {
                registry.put(clsId, factoryEntry.getValue());
            } else {
                // @todo: what to do with already registered ObjectFactory instances? overwrite?
            }
        }

    }
}

From source file:org.passay.SpringTest.java

/**
 * Attempts to load all Spring application context XML files to verify proper wiring.
 *
 * @throws  Exception  On test failure./*ww  w . ja va  2  s  . c  om*/
 */
@Test(groups = { "passtest" })
public void testSpringWiring() throws Exception {
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "/spring-context.xml", });
    AssertJUnit.assertTrue(context.getBeanDefinitionCount() > 0);

    final PasswordValidator validator = new PasswordValidator(
            new ArrayList<>(context.getBeansOfType(Rule.class).values()));
    final PasswordData pd = new PasswordData("springtest");
    pd.setUsername("springuser");

    final RuleResult result = validator.validate(pd);
    AssertJUnit.assertNotNull(result);
}

From source file:edu.vt.middleware.password.SpringTest.java

/**
 * Attempts to load all Spring application context XML files to verify proper
 * wiring./*from  w  w w. j  av  a 2 s .  c om*/
 *
 * @throws  Exception  On test failure.
 */
@Test(groups = { "passtest" })
public void testSpringWiring() throws Exception {
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "/spring-context.xml", });
    AssertJUnit.assertTrue(context.getBeanDefinitionCount() > 0);

    final PasswordValidator validator = new PasswordValidator(
            new ArrayList<Rule>(context.getBeansOfType(Rule.class).values()));
    final PasswordData pd = new PasswordData(new Password("springtest"));
    pd.setUsername("springuser");

    final RuleResult result = validator.validate(pd);
    AssertJUnit.assertNotNull(result);
}

From source file:org.brutusin.jsonsrv.SpringJsonServlet.java

@Override
protected Map<String, JsonAction> loadActions() throws Exception {
    String springConfigFile = getServletConfig().getInitParameter(INIT_PARAM_SPRING_CFG_FILE);
    ClassPathXmlApplicationContext applicationContext;
    if (springConfigFile == null) {
        applicationContext = new ClassPathXmlApplicationContext(DEFAULT_CFG_FILE);
    } else {//  w  w  w.  j ava2 s.co m
        applicationContext = new ClassPathXmlApplicationContext(springConfigFile, DEFAULT_CFG_FILE);
    }
    applicationContext.setClassLoader(getClassLoader());
    return applicationContext.getBeansOfType(JsonAction.class);
}

From source file:guru.qas.martini.annotation.StepsAnnotationProcessorTest.java

@Test
public void testMultipleGivenRegex() throws NoSuchMethodException {
    MultipleGivenBean source = new MultipleGivenBean();
    ClassPathXmlApplicationContext context = getContext(source);
    process(context, source);//from   w  w  w  .  jav a 2 s.  com

    MultipleGivenBean steps = context.getBean(MultipleGivenBean.class);
    Class<?> wrapped = AopUtils.getTargetClass(steps);
    Method method = wrapped.getMethod("doSomething");

    Map<String, StepImplementation> givenBeanIndex = context.getBeansOfType(StepImplementation.class);
    Collection<StepImplementation> givens = givenBeanIndex.values();

    Set<String> matches = Sets.newHashSetWithExpectedSize(2);
    for (StepImplementation given : givens) {
        Method givenMethod = given.getMethod();
        if (givenMethod.equals(method)) {
            Pattern pattern = given.getPattern();
            String regex = pattern.pattern();
            matches.add(regex);
        }
    }

    int count = matches.size();
    assertEquals(count, 2, "wrong number of GivenStep objects registered for MultipleGivenBean.getMartinis()");

    Set<String> expected = Sets.newHashSet("this is regular expression one", "this is regular expression two");
    assertEquals(matches, expected, "Steps contain wrong regex Pattern objects");
}

From source file:guru.qas.martini.annotation.StepsAnnotationProcessorTest.java

@Test
public void testPostProcessAfterInitialization() throws IOException, NoSuchMethodException {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    TestSteps steps = context.getBean(TestSteps.class);

    Class<?> wrapped = AopUtils.getTargetClass(steps);
    Method method = wrapped.getMethod("anotherStep", String.class);

    Map<String, StepImplementation> givenBeanIndex = context.getBeansOfType(StepImplementation.class);
    Collection<StepImplementation> givens = givenBeanIndex.values();

    List<StepImplementation> matches = Lists.newArrayList();
    for (StepImplementation given : givens) {
        Method givenMethod = given.getMethod();
        if (givenMethod.equals(method)) {
            matches.add(given);//from w  ww.  j a  v  a2 s.  c  o  m
        }
    }

    int count = matches.size();
    assertEquals(count, 1, "wrong number of GivenStep objects registered for TestSteps.anotherStep()");

    StepImplementation match = matches.get(0);
    Pattern pattern = match.getPattern();
    Matcher matcher = pattern.matcher("another \"(.+)\" here");
    assertTrue(matcher.find(), "expected Pattern to match Gherkin regular expression");
    assertEquals(matcher.groupCount(), 1, "wrong number of parameters captured for TestSteps.anotherStep()");
}

From source file:org.ff4j.cli.FF4jCliProcessor.java

/**
 * Parse Spring context.//  ww  w  .  jav  a  2 s . c  om
 */
@SuppressWarnings("unchecked")
public void parseSpringContext(String fileName) {
    try {
        logInfo("Loading configurations from classpath file [" + fileName + "]");
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(fileName);
        this.envs = ctx.getBeansOfType(FF4j.class);
        if (ctx.containsBean("AUTHORIZED_USERS")) {
            this.users = (Map<String, String>) ctx.getBean("AUTHORIZED_USERS");
        }
        ctx.close();
    } catch (RuntimeException fne) {
        error(fne, "Cannot parse Spring context");
    }
}

From source file:org.bpmscript.integration.spring.SpringReplyTest.java

@SuppressWarnings("unchecked")
public void testReply() throws Exception {

    int total = 1;
    final int loopcount = 2;
    final CountDownLatch latch = new CountDownLatch(total + loopcount * total);

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/integration/spring/spring.xml");

    try {/*  www .j av a2 s  .  c  o  m*/

        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");
        final ChannelRegistry channelRegistry = (ChannelRegistry) ((Map) context
                .getBeansOfType(ChannelRegistry.class)).values().iterator().next();

        processManager.createDefinition("id",
                new JavascriptProcessDefinition("test", StreamService.DEFAULT_INSTANCE
                        .getResourceAsString("/org/bpmscript/integration/spring/reply.js")));
        engine.setInstanceListener(new LoggingInstanceListener() {
            @Override
            public void instanceCompleted(String pid, ICompletedResult result) {
                super.instanceCompleted(pid, result);
                latch.countDown();
            }

            @Override
            public void instanceFailed(String pid, IFailedResult result) {
                super.instanceFailed(pid, result);
                fail(result.getThrowable().getMessage());
            }
        });

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            @SuppressWarnings("unchecked")
            public void execute(int count) throws Exception {
                GenericMessage<Object[]> message = new GenericMessage<Object[]>(new Object[] { loopcount });
                message.getHeader().setAttribute("definitionName", "test");
                message.getHeader().setAttribute("operation", "test");
                message.getHeader().setReturnAddress("channel-recorder");
                MessageChannel channel = channelRegistry.lookupChannel("channel-bpmscript-first");
                channel.send(message);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                latch.await();
            }
        }, false));

        SpringRecorder springRecorder = (SpringRecorder) context.getBean("springRecorder");
        BlockingQueue<Object> messages = springRecorder.getMessages();
        for (int i = 0; i < total; i++) {
            Object poll = messages.poll(1, TimeUnit.SECONDS);
            assertNotNull("should have got to " + total + " but got to " + i, poll);
        }

    } finally {
        context.destroy();
    }

}

From source file:org.bpmscript.integration.spring.SpringLoanBrokerTest.java

License:asdf

@SuppressWarnings("unchecked")
public void testReply() throws Exception {

    int total = 1;
    final CountDownLatch latch = new CountDownLatch(total);

    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "/org/bpmscript/integration/spring/spring.xml");

    try {// w w w . ja  v a  2  s .com

        final BpmScriptEngine engine = (BpmScriptEngine) context.getBean("engine");
        final IVersionedDefinitionManager processManager = (IVersionedDefinitionManager) context
                .getBean("versionedDefinitionManager");
        final ChannelRegistry channelRegistry = (ChannelRegistry) ((Map) context
                .getBeansOfType(ChannelRegistry.class)).values().iterator().next();

        processManager.createDefinition("id",
                new JavascriptProcessDefinition("loanBroker", StreamService.DEFAULT_INSTANCE
                        .getResourceAsString("/org/bpmscript/integration/spring/loanbroker.js")));
        engine.setInstanceListener(new LoggingInstanceListener() {
            @Override
            public void instanceCompleted(String pid, ICompletedResult result) {
                super.instanceCompleted(pid, result);
                latch.countDown();
            }

            @Override
            public void instanceFailed(String pid, IFailedResult result) {
                super.instanceFailed(pid, result);
                fail(result.getThrowable().getMessage());
            }
        });

        IBenchmarkPrinter.STDOUT.print(new Benchmark().execute(total, new IBenchmarkCallback() {
            @SuppressWarnings("unchecked")
            public void execute(int count) throws Exception {
                GenericMessage<Object[]> message = new GenericMessage<Object[]>(
                        new Object[] { new LoanRequest("asdf", 1, 1000) });
                message.getHeader().setAttribute("definitionName", "loanBroker");
                message.getHeader().setAttribute("operation", "requestBestRate");
                message.getHeader().setReturnAddress("channel-recorder");
                MessageChannel channel = channelRegistry.lookupChannel("channel-bpmscript-first");
                channel.send(message);
            }
        }, new IWaitForCallback() {
            public void call() throws Exception {
                latch.await();
            }
        }, false));

        SpringRecorder springRecorder = (SpringRecorder) context.getBean("springRecorder");
        BlockingQueue<Object> messages = springRecorder.getMessages();
        for (int i = 0; i < total; i++) {
            Object poll = messages.poll(1, TimeUnit.SECONDS);
            assertNotNull("should have got to " + total + " but got to " + i, poll);
        }

    } finally {
        context.destroy();
    }

}