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

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

Introduction

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

Prototype

public void setConfigLocation(String location) 

Source Link

Document

Set the config locations for this application context in init-param style, i.e.

Usage

From source file:cn.webank.ecif.index.server.EcifIndexServer.java

/**
 * @param args//from w w w .  j av  a2 s .  c  om
 */
public static void main(String[] args) {
    final EcifIndexServer server = new EcifIndexServer();
    // start spring context;
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();

    context.getEnvironment().setActiveProfiles("product");
    context.setConfigLocation("application.xml");
    context.refresh();
    context.start();

    // thread pool construct
    ThreadPoolTaskExecutor taskThreadPool = context.getBean("taskExecutor", ThreadPoolTaskExecutor.class);

    server.setTaskThreadPool(taskThreadPool);

    ExecutorService fixedThreadPool = context.getBean("fixedTaskExecutor", ExecutorService.class);

    server.setSchedulerThreadPool(fixedThreadPool);

    EcifThreadFactory threadFactory = context.getBean("cn.webank.ecif.index.async.EcifThreadFactory",
            EcifThreadFactory.class);

    server.setThreadFactory(threadFactory);

    Properties props = context.getBean("ecifProperties", java.util.Properties.class);

    WeBankServiceDispatcher serviceDispatcher = context.getBean(
            "cn.webank.framework.biz.service.support.WeBankServiceDispatcher", WeBankServiceDispatcher.class);

    ReloadableResourceBundleMessageSource bundleMessageSource = context.getBean("messageSource",
            ReloadableResourceBundleMessageSource.class);

    String topics = props.getProperty("listener.topics");
    String[] splits = topics.split(",");

    SolaceManager solaceManager = context.getBean("cn.webank.framework.message.SolaceManager",
            SolaceManager.class);
    MessageListener messageLisener = new MessageListener(
            // props.getProperty("listener.queue"),
            Arrays.asList(splits), Integer.parseInt(props.getProperty("listener.scanintervalseconds", "5")),
            taskThreadPool, Integer.parseInt(props.getProperty("listener.timeoutseconds", "5")),
            serviceDispatcher, solaceManager, bundleMessageSource);
    server.addListenerOnSchedule(messageLisener);

    // register shutdownhook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                // close resource
                if (context != null) {
                    context.close();
                }

            } catch (Exception e) {
                LOG.error("shutdown error", e);
            }
        }
    });

    // hold server
    try {
        LOG.info("ecif-index server start ok!");
        server.start();
    } catch (Exception e) {
        try {
            // close resource
            server.shutDown();
            if (context != null) {
                context.close();
            }

        } catch (Exception ex) {
            LOG.error("shutdown error", ex);
        }
    }

    LOG.info("ecif-index server stop !");
}

From source file:com.setronica.ucs.server.MessageServer.java

private static ClassPathXmlApplicationContext initApplication(String profile,
        DefaultListableBeanFactory parentBeanFactory) {
    ClassPathXmlApplicationContext applicationContext;

    if (parentBeanFactory != null) {
        //wrap BeanFactory inside ApplicationContext
        GenericApplicationContext parentContext = new GenericApplicationContext(parentBeanFactory);
        parentContext.refresh();/*from ww  w  .j a va2 s  .  c  om*/
        applicationContext = new ClassPathXmlApplicationContext(parentContext);
    } else {
        applicationContext = new ClassPathXmlApplicationContext();
    }
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    environment.setDefaultProfiles(profile);
    applicationContext.setConfigLocation("spring-application.xml");

    // log active profile

    String[] profiles = environment.getActiveProfiles();
    if (profiles.length == 0) {
        profiles = environment.getDefaultProfiles();
    }
    for (String activeProfile : profiles) {
        if (environment.acceptsProfiles(activeProfile)) {
            logger.info("Profile " + activeProfile + " is active");
        }
    }

    applicationContext.refresh();
    return applicationContext;
}

From source file:org.cometd.annotation.spring.SpringAnnotationTest.java

@Test
public void testSpringWiringOfCometDServices() throws Exception {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();
    applicationContext.setConfigLocation("classpath:applicationContext.xml");
    applicationContext.refresh();/*w w  w  . j a  v a  2 s. c  o m*/

    String beanName = Introspector.decapitalize(SpringBayeuxService.class.getSimpleName());

    String[] beanNames = applicationContext.getBeanDefinitionNames();
    assertTrue(Arrays.asList(beanNames).contains(beanName));

    SpringBayeuxService service = (SpringBayeuxService) applicationContext.getBean(beanName);
    assertNotNull(service);
    assertNotNull(service.dependency);
    assertNotNull(service.bayeuxServer);
    assertNotNull(service.serverSession);
    assertTrue(service.active);
    assertEquals(1, service.bayeuxServer.getChannel(SpringBayeuxService.CHANNEL).getSubscribers().size());

    applicationContext.close();

    assertFalse(service.active);
}

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

private ClassPathXmlApplicationContext getApplicationContext() {

    //We need to use ClassPathXmlApplicationContext here and pass a ClassLoader because
    //every plugin has his own classloader and Spring won't be able to find the xml file in
    //the default system classloader

    ClassLoader classLoader = this.getClass().getClassLoader();
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
    ctx.setClassLoader(classLoader);/*from w ww  .  java 2 s  .c  o m*/
    ctx.setConfigLocation("spring-context.xml");
    ctx.refresh();
    return ctx;
}

From source file:org.datalift.sdmxdatacube.SDMXDataCubeModel.java

/**
 * Creates a new SDMXDataCubeModel instance.
 * //from  w w  w .  j  a  v a 2  s . c  om
 * @param name
 *            Name of the module.
 */
public SDMXDataCubeModel(String name) {
    super(name);

    // Initialize the sdmxDataCubeTransformer, which is a Spring bean.
    // It is also referenced in spring-beans.xml.
    Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
    ctx.setConfigLocation("spring/spring-beans.xml");
    ctx.refresh();

    sdmxDataCubeTransformer = ctx.getBean(SDMXDataCubeTransformer.class);
}

From source file:net.dfs.remote.main.ClientServicesStarter.java

public final void loadNode() {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setProperties(props);//from  w ww  .ja v a2  s . c o m

    context.addBeanFactoryPostProcessor(configurer);
    context.setConfigLocation("net\\dfs\\remote\\filestorage\\spring-client.xml");
    context.refresh();
    context.start();

    /*      FileLocationTrackerImpl hash = new FileLocationTrackerImpl();
          hash.removeAll();
    */
    log.info("Client Started");

    FileReceiverSupport receiveFile = (FileReceiverSupport) context.getBean("receiveFile");

    receiveFile.connectJavaSpace();
    receiveFile.retrieveFile();
}

From source file:org.cleverbus.core.common.extension.AbstractExtensionConfigurationLoader.java

private void loadExtension(String extConfigLocation, int extNumber) throws Exception {
    Log.debug("new extension context for '" + extConfigLocation + "' started ...");

    ClassPathXmlApplicationContext extContext = new ClassPathXmlApplicationContext(parentContext);
    extContext.setId("CleverBus extension nr. " + extNumber);
    extContext.setDisplayName("CleverBus extension context for '" + extConfigLocation + '"');
    extContext.setConfigLocation(extConfigLocation);

    extContext.refresh();//from   www. jav  a 2 s  .com

    // add routes into Camel context
    if (isAutoRouteAdding()) {
        Map<String, AbstractExtRoute> beansOfType = extContext.getBeansOfType(AbstractExtRoute.class);
        for (Map.Entry<String, AbstractExtRoute> entry : beansOfType.entrySet()) {
            AbstractExtRoute route = entry.getValue();

            // note: route with existing route ID will override the previous one
            //  it's not possible automatically change route ID before adding to Camel context
            camelContext.addRoutes(route);
        }
    }

    Log.debug("new extension context for '" + extConfigLocation + "' was successfully created");
}

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   ww  w  . j a v  a2s.  co m
        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:nl.nn.adapterframework.configuration.IbisContext.java

/**
 * Create Spring Bean factory. Parameter 'springContext' can be null.
 *
 * Create the Spring Bean Factory using the supplied <code>springContext</code>,
 * if not <code>null</code>.
 *
 * @param springContext Spring Context to create. If <code>null</code>,
 * use the default spring context./*from ww  w.  j a va2s  . c o m*/
 * The spring context is loaded as a spring ClassPathResource from
 * the class path.
 *
 * @return The Spring XML Bean Factory.
 * @throws BeansException If the Factory can not be created.
 *
 */
private ApplicationContext createApplicationContext() throws BeansException {
    // Reading in Spring Context
    long start = System.currentTimeMillis();
    String springContext = "/springContext.xml";
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();
    MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
    propertySources.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
    propertySources.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
    propertySources.addFirst(new PropertiesPropertySource("ibis", APP_CONSTANTS));
    applicationContext.setConfigLocation(springContext);
    applicationContext.refresh();
    log("startup " + springContext + " in " + (System.currentTimeMillis() - start) + " ms");
    return applicationContext;
}

From source file:org.springframework.data.neo4j.illegal.aspects.index1.IllegalIndex1Tests.java

/**
 * As the first illegal entity detected will blow up the application context - we need a way
 * to ensure only the illegal entity under test it loaded to assert that we fail
 * for the correct reason and in an appropriate way. This method will create and application
 * context ensuring that only the illegal entity under test (passed in as an argument), is
 * detected by the context.  This is currently done by wrapping each Illegal Entity bootstrap
 * logic in a Spring profile against its same name
 *
 * @param entityUnderTest Class which should be detected by SDN for the purposes of testing
 * @throws Throwable// ww w  .j  av a2 s  .  c o  m
 */
private void createAppCtxAndPropagateRootExceptionIfThrown(Class entityUnderTest) throws Throwable {
    try {
        ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext();
        appCtx.setConfigLocation(
                "org/springframework/data/neo4j/aspects/support/illegal-index1-tests-context.xml");
        appCtx.getEnvironment().setActiveProfiles(entityUnderTest.getSimpleName());
        appCtx.refresh();
    } catch (BeanCreationException bce) {
        throw ExceptionUtils.getRootCause(bce);
    }
}