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

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

Introduction

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

Prototype

@Override
    public final ConfigurableListableBeanFactory getBeanFactory() 

Source Link

Usage

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

private static ClassPathXmlApplicationContext getContext(Object... beans) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("emptyContext.xml");
    ConfigurableListableBeanFactory factory = context.getBeanFactory();
    for (Object bean : beans) {
        factory.registerSingleton(bean.getClass().getName(), bean);
    }//ww  w .  j a v a2s  .  c o m
    return context;
}

From source file:com.hivemq.plugin.springexample.ExamplePluginModule.java

/**
 * This method is provided to execute some custom plugin configuration stuff. Is is the place
 * to execute Google Guice bindings,etc if needed.
 *//*from  w  w  w  .  j av a 2s . c  o m*/
@Override
protected void configurePlugin() {

    ClassPathXmlApplicationContext ctx = getApplicationContext();

    //Make all instances managed by Spring known to Guice
    SpringIntegration.bindAll(binder(), ctx.getBeanFactory());

    //Make Spring's ApplicationContext known to Guice
    bind(ApplicationContext.class).toInstance(ctx);

    //Tell Guice to inject into the StartCallback instance, which is managed by Spring
    requestInjection(ctx.getBeanFactory().getBean("startCallback"));
}

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

@Test(expectedExceptions = FatalBeanException.class)
public void testNonSingletonSteps() {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("emptyContext.xml");
    ConfigurableListableBeanFactory factory = context.getBeanFactory();

    GenericBeanDefinition definition = new GenericBeanDefinition();
    definition.setBeanClass(DuplicateGivenBeanA.class);
    definition.setLazyInit(false);/*from   w  ww . ja  va  2s  . c  o m*/
    definition.setScope("prototype");

    BeanDefinitionRegistry registry = BeanDefinitionRegistry.class.cast(factory);
    registry.registerBeanDefinition(DuplicateGivenBeanA.class.getName(), definition);
    process(context, new DuplicateGivenBeanA());
}

From source file:com.enterra.batch.admin.sample.BootstrapTests.java

@Test
public void testServletConfiguration() throws Exception {
    ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext(
            "classpath:/org/springframework/batch/admin/web/resources/webapp-config.xml");
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "classpath:/org/springframework/batch/admin/web/resources/servlet-config.xml" },
            parent);/*w  ww  . java 2 s. co  m*/

    assertTrue(context.containsBean("jobRepository"));
    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(),
            JobController.class);
    assertEquals(1, beanNames.length);

    Job job = context.getBean(JobRegistry.class).getJob("job1");
    final JobExecution jobExecution = parent.getBean(JobLauncher.class).run(job,
            new JobParametersBuilder().addString("fail", "false").toJobParameters());

    new DirectPoller<BatchStatus>(100).poll(new Callable<BatchStatus>() {
        public BatchStatus call() throws Exception {
            BatchStatus status = jobExecution.getStatus();
            if (status.isLessThan(BatchStatus.STOPPED) && status != BatchStatus.COMPLETED) {
                return null;
            }
            return status;
        }
    }).get(2000, TimeUnit.MILLISECONDS);

    context.close();
    parent.close();

    assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());

}

From source file:org.jboss.seam.spring.extension.SpringContextBootstrapExtension.java

public void loadSpringContext(@Observes BeforeBeanDiscovery beforeBeanDiscovery, BeanManager beanManager) {
    InputStream inputStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(Locations.SEAM_SPRING_CONTEXTS_LOCATION);
    if (inputStream != null) {
        Properties contextLocations = new Properties();
        try {/*from  ww  w .  ja v a 2 s .c o  m*/
            contextLocations.load(inputStream);
            for (String contextName : contextLocations.stringPropertyNames()) {
                ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                        contextLocations.getProperty(contextName));
                contextDefinitions.put(contextName, context);
                for (String beanDefinitionName : context.getBeanDefinitionNames()) {
                    vetoedTypes.add(
                            context.getBeanFactory().getBeanDefinition(beanDefinitionName).getBeanClassName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

From source file:org.pentaho.pat.plugin.PatLifeCycleListener.java

public void loaded() throws PluginLifecycleException {
    ClassLoader origContextClassloader = Thread.currentThread().getContextClassLoader();
    IServiceManager serviceManager = (IServiceManager) PentahoSystem.get(IServiceManager.class,
            PentahoSessionHolder.getSession());
    try {//from  w w w .ja v a  2 s .c om
        sessionBean = (SessionServlet) serviceManager.getServiceBean("gwt", "session.rpc"); //$NON-NLS-1$
        queryBean = (QueryServlet) serviceManager.getServiceBean("gwt", "query.rpc"); //$NON-NLS-1$
        discoveryBean = (DiscoveryServlet) serviceManager.getServiceBean("gwt", "discovery.rpc"); //$NON-NLS-1$
        platformBean = (PlatformServlet) serviceManager.getServiceBean("gwt", "platform.rpc"); //$NON-NLS-1$

        final IPluginManager pluginManager = (IPluginManager) PentahoSystem.get(IPluginManager.class,
                PentahoSessionHolder.getSession());
        final PluginClassLoader pluginClassloader = (PluginClassLoader) pluginManager
                .getClassLoader(PAT_PLUGIN_NAME);
        final String hibernateConfigurationFile = PentahoSystem
                .getSystemSetting("hibernate/hibernate-settings.xml", "settings/config-file", null); //$NON-NLS-1$
        final String pentahoHibConfigPath = PentahoSystem.getApplicationContext()
                .getSolutionPath(hibernateConfigurationFile);

        if (pluginClassloader == null)
            throw new ServiceException(Messages.getString("LifeCycleListener.NoPluginClassloader")); //$NON-NLS-1$

        Thread.currentThread().setContextClassLoader(pluginClassloader);
        final URL contextUrl = pluginClassloader.getResource(PAT_APP_CONTEXT);
        final URL patHibConfigUrl = pluginClassloader.getResource(PAT_HIBERNATE_CONFIG);
        final URL patPluginPropertiesUrl = pluginClassloader.getResource(PAT_PLUGIN_PROPERTIES);
        if (patHibConfigUrl == null)
            throw new ServiceException("File not found: PAT Hibernate Config : " + PAT_HIBERNATE_CONFIG);
        else
            LOG.debug(PAT_PLUGIN_NAME + ": PAT Hibernate Config:" + patHibConfigUrl.toString());

        if (patPluginPropertiesUrl == null)
            throw new ServiceException("File not found: PAT Plugin properties : " + PAT_PLUGIN_PROPERTIES);
        else
            LOG.debug(PAT_PLUGIN_NAME + ": PAT Plugin Properties:" + patPluginPropertiesUrl.toString());

        if (contextUrl != null) {
            String appContextUrl = contextUrl.toString();
            final ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                    new String[] { appContextUrl }, false);
            applicationContext.setClassLoader(pluginClassloader);
            applicationContext.setConfigLocation(appContextUrl);
            applicationContext.setAllowBeanDefinitionOverriding(true);

            final Configuration pentahoHibConfig = new Configuration();
            pentahoHibConfig.configure(new File(pentahoHibConfigPath));

            final AnnotationConfiguration patHibConfig = new AnnotationConfiguration();
            patHibConfig.configure(patHibConfigUrl);

            Properties properties = new Properties();
            properties.load(pluginClassloader.getResourceAsStream(PAT_PLUGIN_PROPERTIES));
            String hibernateDialectCfg = (String) properties.get("pat.plugin.datasource.hibernate.dialect");
            String hibernateDialect = null;
            if (StringUtils.isNotBlank(hibernateDialectCfg)) {
                if (hibernateDialectCfg.equals("auto")) {
                    hibernateDialect = pentahoHibConfig.getProperty("dialect");
                } else {
                    hibernateDialect = hibernateDialectCfg;
                }
            }

            if (StringUtils.isNotBlank(hibernateDialect)) {
                patHibConfig.setProperty("hibernate.dialect", hibernateDialect);
                LOG.info(PAT_PLUGIN_NAME + " : using hibernate dialect: " + hibernateDialect);
            }

            String dataSourceType = (String) properties.get("pat.plugin.datasource.type");
            String datasourceResource = null;
            if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jdbc")) {
                datasourceResource = PAT_DATASOURCE_JDBC;
                LOG.info(PAT_PLUGIN_NAME + " : using JDBC connection");

            }
            if (StringUtils.isNotEmpty(dataSourceType) && dataSourceType.equals("jndi")) {
                datasourceResource = PAT_DATASOURCE_JNDI;
                LOG.info(PAT_PLUGIN_NAME + " : using JNDI : " + (String) properties.get("jndi.name"));
            }

            XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(datasourceResource));
            PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
            cfg.setLocation(new ClassPathResource(PAT_PLUGIN_PROPERTIES));
            cfg.postProcessBeanFactory(factory);

            XmlBeanFactory bfSession = new XmlBeanFactory(new ClassPathResource(PAT_SESSIONFACTORY), factory);

            PropertyPlaceholderConfigurer cfgSession = new PropertyPlaceholderConfigurer();
            cfgSession.setProperties(patHibConfig.getProperties());
            cfgSession.postProcessBeanFactory(bfSession);

            ClassPathXmlApplicationContext tmpCtxt = new ClassPathXmlApplicationContext();
            tmpCtxt.refresh();
            DefaultListableBeanFactory tmpBf = (DefaultListableBeanFactory) tmpCtxt.getBeanFactory();

            tmpBf.setParentBeanFactory(bfSession);

            applicationContext.setClassLoader(pluginClassloader);
            applicationContext.setParent(tmpCtxt);
            applicationContext.refresh();

            sessionBean.setStandalone(true);
            SessionServlet.setApplicationContext(applicationContext);
            sessionBean.init();

            queryBean.setStandalone(true);
            QueryServlet.setApplicationContext(applicationContext);
            queryBean.init();

            discoveryBean.setStandalone(true);
            DiscoveryServlet.setApplicationContext(applicationContext);
            discoveryBean.init();

            platformBean.setStandalone(true);
            PlatformServlet.setApplicationContext(applicationContext);
            platformBean.init();

            injectPentahoXmlaUrl();
        } else {
            throw new Exception(Messages.getString("LifeCycleListener.AppContextNotFound"));
        }

    } catch (ServiceException e1) {
        LOG.error(e1.getMessage(), e1);
    } catch (ServletException e) {
        LOG.error(e.getMessage(), e);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    } finally {
        // reset the classloader of the current thread
        if (origContextClassloader != null) {
            Thread.currentThread().setContextClassLoader(origContextClassloader);
        }
    }
}

From source file:org.springframework.batch.admin.BootstrapTests.java

@Test
public void testServletConfiguration() throws Exception {
    ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext(
            "classpath:/org/springframework/batch/admin/web/resources/webapp-config.xml");
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "classpath:/org/springframework/batch/admin/web/resources/servlet-config.xml" },
            parent);/*from  w w  w  .  j  a va  2 s  .  c o m*/

    assertTrue(context.containsBean("jobRepository"));
    String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(),
            JobController.class);
    assertEquals(1, beanNames.length);

    MenuManager menuManager = context.getBean(MenuManager.class);
    assertEquals(4, menuManager.getMenus().size());

    context.refresh();

    ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext(
            new String[] { "classpath:/test-job-context.xml" }, parent);
    Job job = child.getBean(Job.class);
    final JobExecution jobExecution = parent.getBean(JobLauncher.class).run(job, new JobParameters());

    new DirectPoller<BatchStatus>(100).poll(new Callable<BatchStatus>() {
        public BatchStatus call() throws Exception {
            BatchStatus status = jobExecution.getStatus();
            if (status.isLessThan(BatchStatus.STOPPED) && status != BatchStatus.COMPLETED) {
                return null;
            }
            return status;
        }
    }).get(2000, TimeUnit.MILLISECONDS);

    HomeController metaData = new HomeController();
    metaData.setApplicationContext(context);
    metaData.afterPropertiesSet();
    MockHttpServletRequest request = new MockHttpServletRequest();
    ModelMap model = new ModelMap();
    metaData.getResources(request, model);
    @SuppressWarnings("unchecked")
    List<ResourceInfo> resources = (List<ResourceInfo>) model.get("resources");
    StringBuilder content = new StringBuilder();
    for (ResourceInfo resourceInfo : resources) {
        content.append(resourceInfo.getMethod() + resourceInfo.getUrl() + "=\n");
    }
    FileUtils.writeStringToFile(new File("target/resources.properties"), content.toString());

    HomeController home = context.getBean(HomeController.class);
    // System.err.println(home.getUrlPatterns());
    assertTrue(home.getUrlPatterns().contains("/jobs/{jobName}"));

    String message = context.getMessage("GET/jobs/{jobName}", new Object[0], Locale.getDefault());
    assertTrue("No message for /jobs/{jobName}", StringUtils.hasText(message));

    child.close();
    context.close();
    parent.close();

    assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());

}