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

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

Introduction

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

Prototype

public void setConfigLocations(@Nullable String... locations) 

Source Link

Document

Set the config locations for this application context.

Usage

From source file:net.sf.gazpachoquest.extractor.dbunit.DBUnitDataExtractorRunner.java

public static void main(final String[] args) throws Exception {
    String dbEngine = "db_postgres";
    logger.info("Extracting data from {} database in DBUnit format", dbEngine);

    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
    ctx.getEnvironment().setActiveProfiles("postgres", dbEngine);
    ctx.refresh();/* w  ww  .  j av a 2 s.com*/
    ctx.setConfigLocations(
            new String[] { "dbunitextractor-datasource-context.xml", "dbunitextractor-context.xml" });
    /*-
    ctx.getEnvironment().getPropertySources()
        .addLast(new ResourcePropertySource(String.format("classpath:/database/%s.properties", dbEngine))); */
    ctx.refresh();

    DBUnitDataExtractor extractor = (DBUnitDataExtractor) ctx.getBean("dbUnitDataExtractor");
    extractor.extract();
    ctx.close();

    logger.info("Done successfully. Check your target directory");

}

From source file:com.temenos.interaction.loader.detector.SpringBasedLoaderAction.java

@Override
public void execute(FileEvent<File> dirEvent) {
    LOGGER.debug("Creation of new Spring ApplicationContext based CommandController triggerred by change in",
            dirEvent.getResource().getAbsolutePath());

    Collection<File> jars = FileUtils.listFiles(dirEvent.getResource(), new String[] { "jar" }, true);
    Set<URL> urls = new HashSet();
    for (File f : jars) {
        try {/* www  .  j a va2s  . com*/
            LOGGER.trace("Adding {} to list of URLs to create ApplicationContext from", f.toURI().toURL());
            urls.add(f.toURI().toURL());
        } catch (MalformedURLException ex) {
            // kindly ignore and log
        }
    }
    Reflections reflectionHelper = new Reflections(
            new ConfigurationBuilder().addClassLoader(classloaderFactory.getForObject(dirEvent))
                    .addScanners(new ResourcesScanner()).addUrls(urls));

    Set<String> resources = new HashSet();

    for (String locationPattern : configLocationsPatterns) {
        String regex = convertWildcardToRegex(locationPattern);
        resources.addAll(reflectionHelper.getResources(Pattern.compile(regex)));
    }

    if (!resources.isEmpty()) {
        // if resources are empty just clean up the previous ApplicationContext and leave!
        LOGGER.debug("Detected potential Spring config files to load");
        ClassPathXmlApplicationContext context;
        if (parentContext != null) {
            context = new ClassPathXmlApplicationContext(parentContext);
        } else {
            context = new ClassPathXmlApplicationContext();
        }

        context.setConfigLocations(configLocationsPatterns.toArray(new String[] {}));

        ClassLoader childClassLoader = classloaderFactory.getForObject(dirEvent);
        context.setClassLoader(childClassLoader);
        context.refresh();

        CommandController cc = null;

        try {
            cc = context.getBean(commandControllerBeanName, CommandController.class);
            LOGGER.debug("Detected pre-configured CommandController in added config files");
        } catch (BeansException ex) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("No detected pre-configured CommandController in added config files.", ex);
            }
            Map<String, InteractionCommand> commands = context.getBeansOfType(InteractionCommand.class);
            if (!commands.isEmpty()) {
                LOGGER.debug("Adding new commands");
                SpringContextBasedInteractionCommandController scbcc = new SpringContextBasedInteractionCommandController();
                scbcc.setApplicationContext(context);
                cc = scbcc;
            } else {
                LOGGER.debug("No commands detected to be added");
            }
        }

        if (parentChainingCommandController != null) {
            List<CommandController> newCommandControllers = new ArrayList<CommandController>(
                    parentChainingCommandController.getCommandControllers());

            // "unload" the previously loaded CommandController
            if (previouslyAddedCommandController != null) {
                LOGGER.debug("Removing previously added instance of CommandController");
                newCommandControllers.remove(previouslyAddedCommandController);
            }

            // if there is a new CommandController on the Spring file, add it on top of the chain
            if (cc != null) {
                LOGGER.debug("Adding newly created CommandController to ChainingCommandController");
                newCommandControllers.add(0, cc);
                parentChainingCommandController.setCommandControllers(newCommandControllers);
                previouslyAddedCommandController = cc;
            } else {
                previouslyAddedCommandController = null;
            }
        } else {
            LOGGER.debug(
                    "No ChainingCommandController set to add newly created CommandController to - skipping action");
        }

        if (previousAppCtx != null) {
            if (previousAppCtx instanceof Closeable) {
                try {
                    ((Closeable) previousAppCtx).close();
                } catch (Exception ex) {
                    LOGGER.error("Error closing the ApplicationContext.", ex);
                }
            }
            previousAppCtx = context;
        }
    } else {
        LOGGER.debug("No Spring config files detected in the JARs scanned");
    }
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private ApplicationContext loadContext(String[] configLocations, URLClassLoader cl, String contextDisplayName,
        Properties properties) throws Exception {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) this._applicationContext)
            .getServletContext();/*  w  w  w  .  j  a va2 s  .  c  o  m*/
    //if plugin's classes have been loaded we can go on
    List<ClassPathXmlApplicationContext> ctxList = (List<ClassPathXmlApplicationContext>) servletContext
            .getAttribute("pluginsContextsList");
    if (ctxList == null) {
        ctxList = new ArrayList<ClassPathXmlApplicationContext>();
        servletContext.setAttribute("pluginsContextsList", ctxList);
    }
    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
    ClassPathXmlApplicationContext newContext = null;
    try {
        //create a new spring context with the classloader and the paths defined as parameter in pluginsInstallerContext.xml.
        //The new context is given the default webapplication context as its parent  
        Thread.currentThread().setContextClassLoader(cl);
        newContext = new ClassPathXmlApplicationContext();
        //ClassPathXmlApplicationContext newContext = new ClassPathXmlApplicationContext(configLocations, applicationContext);    
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        configurer.setProperties(properties);
        newContext.addBeanFactoryPostProcessor(configurer);
        newContext.setClassLoader(cl);
        newContext.setParent(this._applicationContext);
        String[] configLocs = new String[] { "classpath:spring/restServerConfig.xml",
                "classpath:spring/baseSystemConfig.xml" };
        newContext.setConfigLocations(configLocs);
        newContext.refresh();
        BaseConfigManager baseConfigManager = (BaseConfigManager) ((ConfigurableWebApplicationContext) this._applicationContext)
                .getBean("BaseConfigManager");
        baseConfigManager.init();
        newContext.setConfigLocations(configLocations);
        newContext.refresh();
        newContext.setDisplayName(contextDisplayName);
        ClassPathXmlApplicationContext currentCtx = (ClassPathXmlApplicationContext) this
                .getStoredContext(contextDisplayName);
        if (currentCtx != null) {
            currentCtx.close();
            ctxList.remove(currentCtx);
        }
        ctxList.add(newContext);

    } catch (Exception e) {
        _logger.error("Unexpected error loading application context: " + e.getMessage());
        e.printStackTrace();
        throw e;
    } finally {
        Thread.currentThread().setContextClassLoader(currentClassLoader);
    }
    return newContext;
}

From source file:org.jumpmind.symmetric.ClientSymmetricEngine.java

@Override
protected void init() {
    try {//  w  ww.  j ava  2  s . c o  m
        LogSummaryAppenderUtils.registerLogSummaryAppender();

        super.init();

        this.dataSource = platform.getDataSource();

        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        configurer.setProperties(parameterService.getAllParameters());

        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(springContext);
        ctx.addBeanFactoryPostProcessor(configurer);

        List<String> extensionLocations = new ArrayList<String>();
        extensionLocations.add("classpath:/symmetric-ext-points.xml");
        if (registerEngine) {
            extensionLocations.add("classpath:/symmetric-jmx.xml");
        }

        String xml = parameterService.getString(ParameterConstants.EXTENSIONS_XML);
        File file = new File(parameterService.getTempDirectory(), "extension.xml");
        FileUtils.deleteQuietly(file);
        if (isNotBlank(xml)) {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setValidating(false);
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                // the "parse" method also validates XML, will throw an exception if misformatted
                builder.parse(new InputSource(new StringReader(xml)));
                FileUtils.write(file, xml, false);
                extensionLocations.add("file:" + file.getAbsolutePath());
            } catch (Exception e) {
                log.error("Invalid " + ParameterConstants.EXTENSIONS_XML + " parameter.");
            }
        }

        try {
            ctx.setConfigLocations(extensionLocations.toArray(new String[extensionLocations.size()]));
            ctx.refresh();

            this.springContext = ctx;

            ((ClientExtensionService) this.extensionService).setSpringContext(springContext);
            this.extensionService.refresh();
        } catch (Exception ex) {
            log.error(
                    "Failed to initialize the extension points.  Please fix the problem and restart the server.",
                    ex);
        }
    } catch (RuntimeException ex) {
        destroy();
        throw ex;
    }
}

From source file:org.oscarehr.labs.alberta.CLSHandlerIntegrationTest.java

@BeforeClass
public static void init() throws Exception {
    SchemaUtils.restoreAllTables();// ww w .  j  av  a 2  s.co m

    if (SpringUtils.beanFactory == null) {
        oscar.OscarProperties p = oscar.OscarProperties.getInstance();
        p.setProperty("db_name",
                ConfigUtils.getProperty("db_schema") + ConfigUtils.getProperty("db_schema_properties"));
        p.setProperty("db_username", ConfigUtils.getProperty("db_user"));
        p.setProperty("db_password", ConfigUtils.getProperty("db_password"));
        p.setProperty("db_uri", ConfigUtils.getProperty("db_url_prefix"));
        p.setProperty("db_driver", ConfigUtils.getProperty("db_driver"));
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
        context.setConfigLocations(new String[] { "/applicationContext.xml", "/applicationContextBORN.xml" });
        context.refresh();
        SpringUtils.beanFactory = context;
    }

    AuthUtils.initLoginContext();

}

From source file:org.springframework.integration.channel.DirectChannelTests.java

@Test //  See INT-2434
public void testChannelCreationWithBeanDefinitionOverrideTrue() throws Exception {
    ClassPathXmlApplicationContext parentContext = new ClassPathXmlApplicationContext("parent-config.xml",
            this.getClass());
    MessageChannel parentChannelA = parentContext.getBean("parentChannelA", MessageChannel.class);
    MessageChannel parentChannelB = parentContext.getBean("parentChannelB", MessageChannel.class);

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
    context.setAllowBeanDefinitionOverriding(false);
    context.setConfigLocations(
            new String[] { "classpath:org/springframework/integration/channel/channel-override-config.xml" });
    context.setParent(parentContext);/* w  ww  .ja v  a2  s.co m*/
    Method method = ReflectionUtils.findMethod(ClassPathXmlApplicationContext.class, "obtainFreshBeanFactory");
    method.setAccessible(true);
    method.invoke(context);
    assertFalse(context.containsBean("channelA"));
    assertFalse(context.containsBean("channelB"));
    assertTrue(context.containsBean("channelC"));
    assertTrue(context.containsBean("channelD"));

    context.refresh();

    PublishSubscribeChannel channelEarly = context.getBean("channelEarly", PublishSubscribeChannel.class);

    assertTrue(context.containsBean("channelA"));
    assertTrue(context.containsBean("channelB"));
    assertTrue(context.containsBean("channelC"));
    assertTrue(context.containsBean("channelD"));
    EventDrivenConsumer consumerA = context.getBean("serviceA", EventDrivenConsumer.class);
    assertEquals(context.getBean("channelA"), TestUtils.getPropertyValue(consumerA, "inputChannel"));
    assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerA, "handler.outputChannel"));

    EventDrivenConsumer consumerB = context.getBean("serviceB", EventDrivenConsumer.class);
    assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerB, "inputChannel"));
    assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerB, "handler.outputChannel"));

    EventDrivenConsumer consumerC = context.getBean("serviceC", EventDrivenConsumer.class);
    assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerC, "inputChannel"));
    assertEquals(context.getBean("channelD"), TestUtils.getPropertyValue(consumerC, "handler.outputChannel"));

    EventDrivenConsumer consumerD = context.getBean("serviceD", EventDrivenConsumer.class);
    assertEquals(parentChannelA, TestUtils.getPropertyValue(consumerD, "inputChannel"));
    assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerD, "handler.outputChannel"));

    EventDrivenConsumer consumerE = context.getBean("serviceE", EventDrivenConsumer.class);
    assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerE, "inputChannel"));

    EventDrivenConsumer consumerF = context.getBean("serviceF", EventDrivenConsumer.class);
    assertEquals(channelEarly, TestUtils.getPropertyValue(consumerF, "inputChannel"));
}