Example usage for org.springframework.context.support GenericApplicationContext GenericApplicationContext

List of usage examples for org.springframework.context.support GenericApplicationContext GenericApplicationContext

Introduction

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

Prototype

public GenericApplicationContext(@Nullable ApplicationContext parent) 

Source Link

Document

Create a new GenericApplicationContext with the given parent.

Usage

From source file:org.craftercms.deployer.impl.TargetResolverImpl.java

protected ConfigurableApplicationContext loadApplicationContext(HierarchicalConfiguration config,
        File customDeploymentAppContextFile) throws IOException {
    GenericApplicationContext appContext = new GenericApplicationContext(mainApplicationContext);

    MutablePropertySources propertySources = appContext.getEnvironment().getPropertySources();
    propertySources//from  w w w .j a va 2 s.  co m
            .addFirst(new ApacheCommonsConfiguration2PropertySource(CONFIG_PROPERTY_SOURCE_NAME, config));

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

    if (baseTargetAppContextResource.exists()) {
        logger.debug("Loading base target application context at {}", baseTargetAppContextResource);

        reader.loadBeanDefinitions(baseTargetAppContextResource);
    }
    if (baseTargetAppContextOverrideResource.exists()) {
        logger.debug("Loading base target application context override at {}", baseTargetAppContextResource);

        reader.loadBeanDefinitions(baseTargetAppContextResource);
    }
    if (customDeploymentAppContextFile.exists()) {
        logger.debug("Loading custom target application context at {}", customDeploymentAppContextFile);

        try (InputStream in = new BufferedInputStream(new FileInputStream(customDeploymentAppContextFile))) {
            reader.loadBeanDefinitions(new InputSource(in));
        }
    }

    appContext.refresh();

    return appContext;
}

From source file:org.exoplatform.container.spring.SpringContainer.java

/**
 * {@inheritDoc}//from ww w  .  ja v  a 2  s  .co m
 */
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void start() {
    ConfigurationManager cm = super.getComponentInstanceOfType(ConfigurationManager.class, false);
    // We check if the component has been defined in the configuration of the current container
    // The goal is to enable the SpringContainer only if it is needed
    Component component = cm.getComponent(ApplicationContextProvider.class);
    if (component == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(
                    "No ApplicationContextProvider has been defined, thus the SpringContainer will be disabled."
                            + " To enable the Spring Integration please define an ApplicationContextProvider");
        }
    } else {
        DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
        bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
        Collection<ComponentAdapter<?>> adapters = delegate.getComponentAdapters();
        for (ComponentAdapter<?> adapter : adapters) {
            Object key = adapter.getComponentKey();
            String name = keyToBeanName(key);
            String factoryName = name + "#factory";
            RootBeanDefinition def = new RootBeanDefinition(adapter.getComponentImplementation(),
                    AbstractBeanDefinition.AUTOWIRE_NO, false);
            def.setScope(BeanDefinition.SCOPE_PROTOTYPE);
            def.setFactoryBeanName(factoryName);
            def.setFactoryMethodName("getInstance");
            def.setLazyInit(true);
            def.setTargetType(adapter.getComponentImplementation());
            if (key instanceof String) {
                def.addQualifier(new AutowireCandidateQualifier(Named.class, key));
            } else if (key instanceof Class<?> && ((Class<?>) key).isAnnotation()) {
                def.addQualifier(new AutowireCandidateQualifier((Class<?>) key));
            } else {
                def.setPrimary(true);
            }
            bf.registerBeanDefinition(name, def);
            bf.registerSingleton(factoryName, new ComponentAdapterFactoryBean(adapter));
        }
        GenericApplicationContext parentContext = new GenericApplicationContext(bf);
        parentContext.refresh();
        ApplicationContextProvider provider = super.getComponentInstanceOfType(ApplicationContextProvider.class,
                false);
        ctx = provider.getApplicationContext(parentContext);
        LOG.info("A SpringContainer has been enabled using the ApplicationContextProvider "
                + provider.getClass());
    }
    super.start();
}

From source file:com.safi.asterisk.handler.SafletEngine.java

public void init() throws SafletEngineException {
    shuttingDown = false;/*from   ww w.  j a  va 2  s.  c om*/
    try {
        initThreadPool();
        if (useSecurityManager)
            installSecurityManager();
        loadEnvironmentProperties();
        loadActionpaks();

        dynamicApplicationContext = new GenericApplicationContext(applicationContext);

        // if (isServerMode())

        if (debuggerLog.isInfoEnabled())
            debuggerLog.info("Management listener started on " + getManagementPort());
        connectionManager.setManagementPort(getManagementPort());
        connectionManager.setUsePing(isUseManagerPing());

        if (environmentProperties.containsKey(PROP_AMI_RETRY_PERIOD)) {
            String period = environmentProperties.getProperty(PROP_AMI_RETRY_PERIOD);
            try {
                connectionManager.setManagerRetryPeriod(Long.valueOf(period));
            } catch (Exception e) {
                log.error("Couldn't set manager retry period", e);
            }
        }
        //      connectionManager.setBindIP(getBindIP());
        initializeDB(getDatabasePort());
        // Give DB time to start

        hookGlobalVars();
        initShutdownHook();
        connectionManager.initSafiServer();
        connectionManager.initManagerConnections();
        connectionManager.initDBResources();
        initSSHD();
    } catch (DBManagerException e) {
        throw new SafletEngineException("Couldn't initialize DBManager: " + e.getCause().getLocalizedMessage(),
                e, SafletEngineException.SafletExceptionCode.SAFISERVER_DB_ERROR);
    }
    try {
        initJMXServer(getManagementPort());
    } catch (Exception e) {
        throw new SafletEngineException("Couldn't initialize JMX Server: " + e.getCause().getLocalizedMessage(),
                e, SafletEngineException.SafletExceptionCode.RMI_ERROR);
    }
    initPoller();
    startPoller();

}

From source file:org.apache.camel.spring.javaconfig.test.JavaConfigContextLoader.java

/**
 * Loads a new {@link ApplicationContext context} based on the supplied {@code locations},
 * configures the context, and finally returns the context in fully <em>refreshed</em> state.
 * <p/>/*from w w w.  j av  a  2  s .  c o m*/
 *
 * Configuration locations are either fully-qualified class names or base package names. These
 * locations will be given to a {@link JavaConfigApplicationContext} for configuration via the
 * {@link JavaConfigApplicationContext#addConfigClass(Class)} and
 * {@link JavaConfigApplicationContext#addBasePackage(String)} methods.
 *
 * @param locations the locations to use to load the application context
 * @return a new application context
 * @throws IllegalArgumentException if any of <var>locations</var> are not valid fully-qualified
 * Class or Package names
 */
public ApplicationContext loadContext(String... locations) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating a JavaConfigApplicationContext for " + Arrays.asList(locations));
    }

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    ArrayList<Class<?>> configClasses = new ArrayList<Class<?>>();
    ArrayList<String> basePackages = new ArrayList<String>();
    for (String location : locations) {
        // if the location refers to a class, use it. Otherwise assume it's a base package name
        try {
            final Class<?> aClass = this.getClass().getClassLoader().loadClass(location);
            configClasses.add(aClass);
        } catch (ClassNotFoundException e) {
            if (Package.getPackage(location) == null) {
                throw new IllegalArgumentException(
                        String.format("A non-existent class or package name was specified: [%s]", location));
            }
            basePackages.add(location);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Setting config classes to " + configClasses);
        logger.debug("Setting base packages to " + basePackages);
    }

    for (Class<?> configClass : configClasses) {
        context.register(configClass);
    }

    for (String basePackage : basePackages) {
        context.scan(basePackage);
    }

    context.refresh();

    // Have to create a child context that implements BeanDefinitionRegistry
    // to pass to registerAnnotationConfigProcessors, since
    // JavaConfigApplicationContext does not
    final GenericApplicationContext gac = new GenericApplicationContext(context);
    AnnotationConfigUtils.registerAnnotationConfigProcessors(gac);
    // copy BeanPostProcessors to the child context
    for (String bppName : context.getBeanFactory().getBeanNamesForType(BeanPostProcessor.class)) {
        gac.registerBeanDefinition(bppName, context.getBeanFactory().getBeanDefinition(bppName));
    }
    gac.refresh();
    gac.registerShutdownHook();

    return gac;
}

From source file:org.craftercms.deployer.impl.DeploymentResolverImpl.java

protected ConfigurableApplicationContext loadApplicationContext(HierarchicalConfiguration config,
        File customDeploymentAppContextFile) throws IOException {
    GenericApplicationContext appContext = new GenericApplicationContext(mainApplicationContext);

    MutablePropertySources propertySources = appContext.getEnvironment().getPropertySources();
    propertySources//  w  w  w. j av  a 2  s  .c o m
            .addFirst(new ApacheCommonsConfiguration2PropertySource(CONFIG_PROPERTY_SOURCE_NAME, config));

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

    if (baseDeploymentAppContextResource.exists()) {
        logger.debug("Loading base deployment application context at {}", baseDeploymentAppContextResource);

        reader.loadBeanDefinitions(baseDeploymentAppContextResource);
    }
    if (baseDeploymentAppContextOverrideResource.exists()) {
        logger.debug("Loading base deployment application context override at {}",
                baseDeploymentAppContextResource);

        reader.loadBeanDefinitions(baseDeploymentAppContextResource);
    }
    if (customDeploymentAppContextFile.exists()) {
        logger.debug("Loading custom deployment application context at {}", customDeploymentAppContextFile);

        try (InputStream in = new BufferedInputStream(new FileInputStream(customDeploymentAppContextFile))) {
            reader.loadBeanDefinitions(new InputSource(in));
        }
    }

    appContext.refresh();

    return appContext;
}

From source file:org.craftercms.deployer.impl.TargetServiceImpl.java

protected ConfigurableApplicationContext loadApplicationContext(HierarchicalConfiguration config,
        File contextFile) throws DeployerConfigurationException {
    GenericApplicationContext context = new GenericApplicationContext(mainApplicationContext);

    MutablePropertySources propertySources = context.getEnvironment().getPropertySources();
    propertySources/*from  w  w  w. j av a2  s.co m*/
            .addFirst(new ApacheCommonsConfiguration2PropertySource(CONFIG_PROPERTY_SOURCE_NAME, config));

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

    if (baseTargetContextResource.exists()) {
        logger.debug("Loading base target application context at {}", baseTargetContextResource);

        try {
            reader.loadBeanDefinitions(baseTargetContextResource);
        } catch (Exception e) {
            throw new DeployerConfigurationException(
                    "Failed to load application context at " + baseTargetContextResource, e);
        }
    }
    if (baseTargetContextOverrideResource.exists()) {
        logger.debug("Loading base target application context override at {}",
                baseTargetContextOverrideResource);

        try {
            reader.loadBeanDefinitions(baseTargetContextOverrideResource);
        } catch (Exception e) {
            throw new DeployerConfigurationException(
                    "Failed to load application context at " + baseTargetContextOverrideResource, e);
        }
    }
    if (contextFile.exists()) {
        logger.debug("Loading target application context at {}", contextFile);

        try (InputStream in = new BufferedInputStream(new FileInputStream(contextFile))) {
            reader.loadBeanDefinitions(new InputSource(in));
        } catch (Exception e) {
            throw new DeployerConfigurationException("Failed to load application context at " + contextFile, e);
        }
    }

    context.refresh();

    return context;
}

From source file:org.craftercms.engine.service.context.SiteContextFactory.java

protected ConfigurableApplicationContext getApplicationContext(SiteContext siteContext,
        URLClassLoader classLoader, HierarchicalConfiguration config, String[] applicationContextPaths,
        ResourceLoader resourceLoader) {
    try {//  w w w.  ja v  a 2 s .co m
        List<Resource> resources = new ArrayList<>();

        for (String path : applicationContextPaths) {
            Resource resource = resourceLoader.getResource(path);
            if (resource.exists()) {
                resources.add(resource);
            }
        }

        if (CollectionUtils.isNotEmpty(resources)) {
            String siteName = siteContext.getSiteName();

            logger.info("--------------------------------------------------");
            logger.info("<Loading application context for site: " + siteName + ">");
            logger.info("--------------------------------------------------");

            GenericApplicationContext appContext = new GenericApplicationContext(mainApplicationContext);
            appContext.setClassLoader(classLoader);

            if (config != null) {
                MutablePropertySources propertySources = appContext.getEnvironment().getPropertySources();
                propertySources.addFirst(new ApacheCommonsConfiguration2PropertySource("siteConfig", config));
            }

            XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext);
            reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);

            for (Resource resource : resources) {
                reader.loadBeanDefinitions(resource);
            }

            appContext.refresh();

            logger.info("--------------------------------------------------");
            logger.info("</Loading application context for site: " + siteName + ">");
            logger.info("--------------------------------------------------");

            return appContext;
        } else {
            return null;
        }
    } catch (Exception e) {
        throw new SiteContextCreationException(
                "Unable to load application context for site '" + siteContext.getSiteName() + "'", e);
    }
}

From source file:org.marketcetera.util.spring.SpringUtilsTest.java

@Test
public void propertiesConfigurerStringSet() {
    GenericApplicationContext context = new GenericApplicationContext(
            new FileSystemXmlApplicationContext(TEST_SPRING_FILE));
    SpringUtils.addPropertiesConfigurer(context, TEST_CONFIGURER_BEAN, TEST_PROPERTIES_FILE_BEAN);
    SpringUtils.addStringBean(context, TEST_NAME_BEAN, "${" + TEST_NAME_PROP + "}");
    context.refresh();/*from   w w w.  j  ava2  s  .  c o  m*/
    assertEquals(TEST_VALUE_PROP, context.getBean(TEST_NAME_BEAN));
}

From source file:org.marketcetera.util.spring.SpringUtilsTest.java

@Test
public void propertiesConfigurerStringUnset() {
    GenericApplicationContext context = new GenericApplicationContext(
            new FileSystemXmlApplicationContext(TEST_SPRING_FILE));
    SpringUtils.addPropertiesConfigurer(context, TEST_CONFIGURER_BEAN, TEST_PROPERTIES_FILE_BEAN);
    SpringUtils.addStringBean(context, TEST_NAME_BEAN, "${" + TEST_NAME_PROP_BLANK + "}");
    context.refresh();/*from   w  w  w  .j  av a 2 s . co  m*/
    assertEquals(StringUtils.EMPTY, context.getBean(TEST_NAME_BEAN));
}