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:co.paralleluniverse.common.spring.SpringContainerHelper.java

public static ConfigurableApplicationContext createContext(String defaultDomain, Resource xmlResource,
        Object properties, BeanFactoryPostProcessor beanFactoryPostProcessor) {
    LOG.info("JAVA: {} {}, {}", new Object[] { System.getProperty("java.runtime.name"),
            System.getProperty("java.runtime.version"), System.getProperty("java.vendor") });
    LOG.info("OS: {} {}, {}", new Object[] { System.getProperty("os.name"), System.getProperty("os.version"),
            System.getProperty("os.arch") });
    LOG.info("DIR: {}", System.getProperty("user.dir"));

    final DefaultListableBeanFactory beanFactory = createBeanFactory();
    final GenericApplicationContext context = new GenericApplicationContext(beanFactory);
    context.registerShutdownHook();//  w w w  .  j av a  2  s. c o m

    final PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
    propertyPlaceholderConfigurer
            .setSystemPropertiesMode(PropertyPlaceholderConfigurer.SYSTEM_PROPERTIES_MODE_OVERRIDE);

    if (properties != null) {
        if (properties instanceof Resource)
            propertyPlaceholderConfigurer.setLocation((Resource) properties);
        else if (properties instanceof Properties)
            propertyPlaceholderConfigurer.setProperties((Properties) properties);
        else
            throw new IllegalArgumentException(
                    "Properties argument - " + properties + " - is of an unhandled type");
    }
    context.addBeanFactoryPostProcessor(propertyPlaceholderConfigurer);

    // MBean exporter
    //final MBeanExporter mbeanExporter = new AnnotationMBeanExporter();
    //mbeanExporter.setServer(ManagementFactory.getPlatformMBeanServer());
    //beanFactory.registerSingleton("mbeanExporter", mbeanExporter);
    context.registerBeanDefinition("mbeanExporter", getMBeanExporterBeanDefinition(defaultDomain));

    // inject bean names into components
    context.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            for (String beanName : beanFactory.getBeanDefinitionNames()) {
                try {
                    final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                    if (beanDefinition.getBeanClassName() != null) { // van be null for factory methods
                        final Class<?> beanClass = Class.forName(beanDefinition.getBeanClassName());
                        if (Component.class.isAssignableFrom(beanClass))
                            beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, beanName);
                    }
                } catch (Exception ex) {
                    LOG.error("Error loading bean " + beanName + " definition.", ex);
                    throw new Error(ex);
                }
            }
        }
    });

    if (beanFactoryPostProcessor != null)
        context.addBeanFactoryPostProcessor(beanFactoryPostProcessor);

    beanFactory.registerCustomEditor(org.w3c.dom.Element.class,
            co.paralleluniverse.common.util.DOMElementProprtyEditor.class);

    final Map<String, Object> beans = new HashMap<String, Object>();

    beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            LOG.info("Loading bean {} [{}]", beanName, bean.getClass().getName());
            beans.put(beanName, bean);

            if (bean instanceof Service) {
                final BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
                Collection<String> dependencies = getBeanDependencies(beanDefinition);

                for (String dependeeName : dependencies) {
                    Object dependee = beanFactory.getBean(dependeeName);
                    if (dependee instanceof Service) {
                        ((Service) dependee).addDependedBy((Service) bean);
                        ((Service) bean).addDependsOn((Service) dependee);
                    }
                }
            }
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            LOG.info("Bean {} [{}] loaded", beanName, bean.getClass().getName());
            return bean;
        }
    });

    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory);
    xmlReader.loadBeanDefinitions(xmlResource);

    // start container
    context.refresh();

    // Call .postInit() on all Components
    // There's probably a better way to do this
    try {
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            final String beanName = entry.getKey();
            final Object bean = entry.getValue();
            if (bean instanceof Component) {
                LOG.info("Performing post-initialization on bean {} [{}]", beanName, bean.getClass().getName());
                ((Component) bean).postInit();
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

    return context;
}

From source file:com.googlecode.shutdownlistener.spring.ApplicationContextShutdownWrapper.java

public ApplicationContextShutdownWrapper(ApplicationContext applicationContext) {
    Assert.notNull(applicationContext, "ApplicationContext cannot be null");
    this.applicationContext = applicationContext;
    if (!(applicationContext instanceof DisposableBean)) {
        throw new IllegalArgumentException("The provided BeanFactory must implement DisposableBean");
    }//  w  ww . j a  va 2 s  . c  o m
    this.disposableBean = (DisposableBean) this.applicationContext;

    ShutdownHandler shutdownHandler = null;
    try {
        shutdownHandler = this.applicationContext.getBean(ShutdownHandlerBean.class);
    } catch (NoSuchBeanDefinitionException e) {
        //Ignore
    }

    if (shutdownHandler != null) {
        this.shutdownHandler = shutdownHandler;
        this.shutdownBeanFactory = null;
    } else {
        this.shutdownBeanFactory = new GenericApplicationContext(this.applicationContext);

        final GenericBeanDefinition shutdownBeanDefinition = new GenericBeanDefinition();
        shutdownBeanDefinition.setBeanClass(ShutdownHandlerBean.class);

        this.shutdownBeanFactory.registerBeanDefinition(ShutdownHandler.class.getName(),
                shutdownBeanDefinition);
        this.shutdownBeanFactory.refresh();

        this.shutdownHandler = this.shutdownBeanFactory.getBean(ShutdownHandler.class);
    }
}

From source file:com.opengamma.component.factory.AbstractSpringComponentFactory.java

/**
 * Creates the application context.// www .  jav  a2s  . c  om
 * 
 * @param repo  the component repository, not null
 * @return the Spring application context, not null
 */
protected GenericApplicationContext createApplicationContext(ComponentRepository repo) {
    Resource springFile = getSpringFile();
    try {
        repo.getLogger().logDebug("  Spring file: " + springFile.getURI());
    } catch (Exception ex) {
        // ignore
    }

    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    GenericApplicationContext appContext = new GenericApplicationContext(beanFactory);

    PropertyPlaceholderConfigurer properties = new PropertyPlaceholderConfigurer();
    properties.setLocation(getPropertiesFile());

    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
    beanDefinitionReader.setValidating(true);
    beanDefinitionReader.setResourceLoader(appContext);
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(appContext));
    beanDefinitionReader.loadBeanDefinitions(springFile);

    appContext.getBeanFactory().registerSingleton("injectedProperties", properties);
    appContext.getBeanFactory().registerSingleton("componentRepository", repo);

    appContext.refresh();
    return appContext;
}

From source file:org.iternine.jeppetto.testsupport.TestContext.java

public TestContext(String configurationFilename, String propertiesFilename,
        DatabaseProvider... databaseProviders) {
    XmlBeanFactory xmlBeanFactory = new XmlBeanFactory(new ClassPathResource(configurationFilename));
    xmlBeanFactory.setBeanClassLoader(this.getClass().getClassLoader());

    Properties properties = new Properties();

    try {//from w  w  w  . j a  v  a2  s  .  co m
        properties.load(new ClassPathResource(propertiesFilename).getInputStream());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (databaseProviders != null) {
        for (DatabaseProvider databaseProvider : databaseProviders) {
            properties = databaseProvider.modifyProperties(properties);
        }
    }

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setProperties(properties);
    configurer.postProcessBeanFactory(xmlBeanFactory);

    try {
        applicationContext = new GenericApplicationContext(xmlBeanFactory);
        applicationContext.refresh();

        if (databaseProviders != null) {
            for (DatabaseProvider databaseProvider : databaseProviders) {
                databases.add(databaseProvider.getDatabase(properties, applicationContext));
            }
        }
    } catch (RuntimeException e) {
        if (databaseProviders != null) {
            for (DatabaseProvider databaseProvider : databaseProviders) {
                if (databaseProvider instanceof Closeable) {
                    try {
                        ((Closeable) databaseProvider).close();
                    } catch (IOException e1) {
                        // ignore
                    }
                }
            }
        }

        throw e;
    }
}

From source file:ch.rasc.wampspring.method.PayloadArgumentResolverTest.java

@SuppressWarnings("resource")
@Before/*from w w w  . j  a v  a2 s  . c om*/
public void setup() throws Exception {
    DefaultListableBeanFactory dlbf = new DefaultListableBeanFactory();
    dlbf.registerSingleton("mvcValidator", testValidator());
    GenericApplicationContext ctx = new GenericApplicationContext(dlbf);
    ctx.refresh();
    this.resolver = new PayloadArgumentResolver(ctx,
            new MethodParameterConverter(new ObjectMapper(), new GenericConversionService()));
    this.payloadMethod = getClass().getDeclaredMethod("handleMessage", String.class, String.class, String.class,
            String.class, String.class, String.class, String.class, Integer.class);

    this.paramAnnotated = getMethodParameter(this.payloadMethod, 0);
    this.paramAnnotatedNotRequired = getMethodParameter(this.payloadMethod, 1);
    this.paramAnnotatedRequired = getMethodParameter(this.payloadMethod, 2);
    this.paramWithSpelExpression = getMethodParameter(this.payloadMethod, 3);
    this.paramValidated = getMethodParameter(this.payloadMethod, 4);
    this.paramValidated.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
    this.paramValidatedNotAnnotated = getMethodParameter(this.payloadMethod, 5);
    this.paramNotAnnotated = getMethodParameter(this.payloadMethod, 6);
}

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 w w w. ja v a2 s  . co  m*/
        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:com.sitewhere.configuration.ExternalConfigurationResolver.java

@Override
public ApplicationContext resolveTenantContext(ITenant tenant, IVersion version, ApplicationContext parent)
        throws SiteWhereException {
    URL remoteTenantUrl = getRemoteTenantUrl(tenant, version);
    GenericApplicationContext context = new GenericApplicationContext(parent);

    // Plug in custom property source.
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("sitewhere.edition", version.getEditionIdentifier().toLowerCase());
    properties.put("tenant.id", tenant.getId());

    MapPropertySource source = new MapPropertySource("sitewhere", properties);
    context.getEnvironment().getPropertySources().addLast(source);

    try {/*  ww w  .  j av  a 2  s . c o  m*/
        // Read context from XML configuration file.
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
        reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
        reader.loadBeanDefinitions(new InputStreamResource(remoteTenantUrl.openStream()));
        context.refresh();
        return context;
    } catch (BeanDefinitionStoreException e) {
        throw new SiteWhereException(e);
    } catch (IOException e) {
        throw new SiteWhereException(e);
    }
}

From source file:com.sitewhere.configuration.TomcatConfigurationResolver.java

@Override
public ApplicationContext resolveTenantContext(ITenant tenant, IVersion version, ApplicationContext global)
        throws SiteWhereException {
    LOGGER.info("Loading Spring configuration ...");
    File sitewhereConf = getSiteWhereConfigFolder();
    File tenantConfigFile = getTenantConfigurationFile(sitewhereConf, tenant, version);
    GenericApplicationContext context = new GenericApplicationContext(global);

    // Plug in custom property source.
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("sitewhere.edition", version.getEditionIdentifier().toLowerCase());
    properties.put("tenant.id", tenant.getId());

    MapPropertySource source = new MapPropertySource("sitewhere", properties);
    context.getEnvironment().getPropertySources().addLast(source);

    // Read context from XML configuration file.
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(context);
    reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
    reader.loadBeanDefinitions(new FileSystemResource(tenantConfigFile));

    context.refresh();/*from   w  w w.  j  a  v a  2s  .c o m*/
    return context;
}

From source file:edu.internet2.middleware.shibboleth.common.config.BaseService.java

/**
 * Loads the service context./*from   w w w .  j av a 2 s. c  om*/
 * 
 * @throws ServiceException thrown if the configuration for this service could not be loaded
 */
protected void loadContext() throws ServiceException {
    log.info("Loading new configuration for service {}", getId());

    if (serviceConfigurations == null || serviceConfigurations.isEmpty()) {
        setInitialized(true);
        return;
    }

    GenericApplicationContext newServiceContext = new GenericApplicationContext(getApplicationContext());
    newServiceContext.setDisplayName("ApplicationContext:" + getId());
    Lock writeLock = getReadWriteLock().writeLock();
    writeLock.lock();
    try {
        SpringConfigurationUtils.populateRegistry(newServiceContext, getServiceConfigurations());
        newServiceContext.refresh();

        GenericApplicationContext replacedServiceContext = serviceContext;
        onNewContextCreated(newServiceContext);
        setServiceContext(newServiceContext);
        setInitialized(true);
        if (replacedServiceContext != null) {
            replacedServiceContext.close();
        }
        log.info("{} service loaded new configuration", getId());
    } catch (Throwable e) {
        // Here we catch all the other exceptions thrown by Spring when it starts up the context
        setInitialized(false);
        Throwable rootCause = e;
        while (rootCause.getCause() != null) {
            rootCause = rootCause.getCause();
        }
        log.error("Configuration was not loaded for " + getId()
                + " service, error creating components.  The root cause of this error was: "
                + rootCause.getClass().getCanonicalName() + ": " + rootCause.getMessage());
        log.trace("Full stacktrace is: ", e);
        throw new ServiceException(
                "Configuration was not loaded for " + getId() + " service, error creating components.",
                rootCause);
    } finally {
        writeLock.unlock();
    }
}

From source file:com.hybris.backoffice.cockpitng.search.DefaultAdvancedSearchOperatorServiceTest.java

@Override
public void prepareApplicationContextAndSession() {
    final ApplicationContext parentApplicationContext = getApplicationContext();
    final GenericApplicationContext applicationContext = new GenericApplicationContext(
            parentApplicationContext);//w  w  w .  java 2s .c o m
    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
    xmlReader.loadBeanDefinitions(new ByteArrayResource(BEANS_DEFINITION.getBytes()));
    applicationContext.refresh();

    autowireProperties(applicationContext);
}