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

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

Introduction

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

Prototype

@Override
    public void refresh() throws BeansException, IllegalStateException 

Source Link

Usage

From source file:de.hybris.platform.btgcockpit.service.BTGCockpitServiceTest.java

public void initApplicationContext() {
    final GenericApplicationContext context = new GenericApplicationContext();
    context.setResourceLoader(new DefaultResourceLoader(Registry.class.getClassLoader()));
    context.setClassLoader(Registry.class.getClassLoader());
    context.getBeanFactory().setBeanClassLoader(Registry.class.getClassLoader());
    context.setParent(Registry.getGlobalApplicationContext());
    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
    xmlReader.setDocumentReaderClass(ScopeTenantIgnoreDocReader.class);
    xmlReader.setBeanClassLoader(Registry.class.getClassLoader());
    xmlReader.loadBeanDefinitions(getSpringConfigurationLocations());
    context.refresh();
    final AutowireCapableBeanFactory beanFactory = context.getAutowireCapableBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
    this.applicationContex = context;
}

From source file:com.github.yihtserns.jaxbean.unmarshaller.api.SpringBeanHandlerTest.java

@Override
protected <T> T unmarshal(String xml, Class<T> rootType, Class<?>... allTypes) throws Exception {
    JaxbeanUnmarshaller unmarshaller = JaxbeanUnmarshaller.newInstance(merge(rootType, allTypes));
    final UnmarshallerNamespaceHandler unmarshallerNamespaceHandler = new UnmarshallerNamespaceHandler(
            unmarshaller);//  w  ww.j a  v  a 2  s .  c  o m

    GenericApplicationContext appContext = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appContext) {

        @Override
        protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() {
            final NamespaceHandlerResolver defaultResolver = super.createDefaultNamespaceHandlerResolver();
            return new NamespaceHandlerResolver() {

                public NamespaceHandler resolve(String namespaceUri) {
                    if (namespaceUri.equals("http://example.com/jaxb")) {
                        return unmarshallerNamespaceHandler;
                    }
                    return defaultResolver.resolve(namespaceUri);
                }
            };
        }
    };
    xmlReader.setValidating(false);
    xmlReader.loadBeanDefinitions(new InputSource(new StringReader(xml)));
    appContext.refresh();

    return appContext.getBean(rootType);
}

From source file:org.uimafit.spring.UimaFactoryInjectionTest.java

private ApplicationContext getApplicationContext() {
    final GenericApplicationContext ctx = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ctx);
    ctx.registerBeanDefinition("otherBean", BeanDefinitionBuilder.genericBeanDefinition(String.class)
            .addConstructorArgValue("BEAN").getBeanDefinition());

    ctx.registerBeanDefinition("analysisEngineFactory",
            BeanDefinitionBuilder.genericBeanDefinition(AnalysisEngineFactory_impl.class).getBeanDefinition());
    ctx.registerBeanDefinition("casConsumerFactory",
            BeanDefinitionBuilder.genericBeanDefinition(CasConsumerFactory_impl.class).getBeanDefinition());
    ctx.registerBeanDefinition("casInitializerFactory",
            BeanDefinitionBuilder.genericBeanDefinition(CasInitializerFactory_impl.class).getBeanDefinition());
    ctx.registerBeanDefinition("collectionReaderFactory", BeanDefinitionBuilder
            .genericBeanDefinition(CollectionReaderFactory_impl.class).getBeanDefinition());
    ctx.registerBeanDefinition("customResourceFactory",
            BeanDefinitionBuilder.genericBeanDefinition(CustomResourceFactory_impl.class).getBeanDefinition());
    ctx.refresh();
    return ctx;//from ww  w .j  av  a  2 s . c  o  m
}

From source file:com.retroduction.carma.application.CarmaTestExecuter.java

public Summary executeTests() {

    CarmaDriverSetup setup = new CarmaDriverSetup();
    Properties customProps = new Properties();
    try {/*w w w.j av  a 2 s  .  co m*/
        customProps.load(new FileInputStream(this.configFile));

    } catch (IOException e) {
        throw new CarmaException("Failed to load configuration", e);
    }

    // merge multiple bean definition sources into application context
    GenericApplicationContext factory = new GenericApplicationContext();

    customProps.setProperty(ICoreConfigConsts.BEAN_REPORTFILE, this.reportFile.getPath());

    // configure maven specific bean references and add beans to parent
    // factory
    // the names in the parent factory should be unique and not overridden
    // by children, otherwise they would have no effect

    customProps.setProperty("project.classesdir.source", BEAN_MAVEN_PROJECT_CLASSES_DIR);
    factory.getBeanFactory().registerSingleton(BEAN_MAVEN_PROJECT_CLASSES_DIR, this.classesDir);

    customProps.setProperty("project.testclassesdir.source", BEAN_MAVEN_PROJECT_TESTCLASSES_DIR);
    factory.getBeanFactory().registerSingleton(BEAN_MAVEN_PROJECT_TESTCLASSES_DIR, this.testClassesDir);

    customProps.setProperty("project.libraries.source", BEAN_MAVEN_PROJECT_LIBRARIES);
    factory.getBeanFactory().registerSingleton(BEAN_MAVEN_PROJECT_LIBRARIES, this.dependencyClassPathUrls);

    setup.setParentContext(factory);
    setup.addCustomConfiguration(customProps);

    // add runtime parameters
    if (this.reportFile.getParentFile() != null) {
        this.reportFile.getParentFile().mkdirs();
    }

    factory.refresh();
    ApplicationContext ctx = setup.getApplicationContext();
    SummaryCreatorEventListener summaryCreator = new SummaryCreatorEventListener();
    ((CompositeEventListener) ctx.getBean("eventListener")).getListeners().add(summaryCreator);

    Core driver = setup.getDriver();
    driver.execute();

    Summary sum = summaryCreator.createSummary();
    return sum;
}

From source file:nz.co.senanque.madura.bundle.BundleRootImpl.java

public void init(DefaultListableBeanFactory ownerBeanFactory, Properties properties, ClassLoader cl,
        Map<String, Object> inheritableBeans) {
    m_properties = properties;// w w  w  . j  a  va2 s  . c  o m
    m_inheritableBeans = inheritableBeans;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(cl);
    m_classLoader = cl;
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    String contextPath = properties.getProperty("Bundle-Context", "/bundle-spring.xml");
    m_logger.debug("loading context: {}", contextPath);
    ClassPathResource classPathResource = new ClassPathResource(contextPath, cl);
    xmlReader.loadBeanDefinitions(classPathResource);
    PropertyPlaceholderConfigurer p = new PropertyPlaceholderConfigurer();
    p.setProperties(properties);
    ctx.addBeanFactoryPostProcessor(p);
    if (m_logger.isDebugEnabled()) {
        dumpClassLoader(cl);
    }
    for (Map.Entry<String, Object> entry : inheritableBeans.entrySet()) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder
                .genericBeanDefinition(InnerBundleFactory.class);
        beanDefinitionBuilder.addPropertyValue("key", entry.getKey());
        beanDefinitionBuilder.addPropertyValue("object", inheritableBeans.get(entry.getKey()));
        ctx.registerBeanDefinition(entry.getKey(), beanDefinitionBuilder.getBeanDefinition());
    }
    Scope scope = ownerBeanFactory.getRegisteredScope("session");
    if (scope != null) {
        ctx.getBeanFactory().registerScope("session", scope);
    }
    ctx.refresh();
    m_applicationContext = ctx;
    Thread.currentThread().setContextClassLoader(classLoader);
}

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  ww .jav a 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.walkmod.conf.providers.SpringConfigurationProvider.java

@Override
public void loadBeanFactory() throws ConfigurationException {

    GenericApplicationContext ctx = new GenericApplicationContext();
    ClassLoader currentClassLoader = configuration.getClassLoader();
    if (currentClassLoader != Thread.currentThread().getContextClassLoader()) {
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(ctx);
        reader.setBeanClassLoader(currentClassLoader);
        reader.loadBeanDefinitions(new ClassPathResource(config, currentClassLoader));
        Collection<PluginConfig> plugins = configuration.getPlugins();
        if (plugins != null) {
            for (PluginConfig plugin : plugins) {
                String descriptorName = plugin.getArtifactId();
                if (!descriptorName.startsWith("walkmod-")) {
                    descriptorName = "walkmod-" + descriptorName;
                }// w  w w . j  a v  a2  s.  com
                if (!descriptorName.endsWith("-plugin")) {
                    descriptorName = descriptorName + "-plugin";
                }

                reader.loadBeanDefinitions(new ClassPathResource("META-INF/walkmod/" + descriptorName + ".xml",
                        configuration.getClassLoader()));

                URL url = currentClassLoader.getResource("META-INF/walkmod2/" + descriptorName + ".xml");
                if (url != null) {
                    reader.loadBeanDefinitions(new ClassPathResource(
                            "META-INF/walkmod2/" + descriptorName + ".xml", configuration.getClassLoader()));
                }
            }
        }
        configuration.setBeanDefinitionRegistry(reader.getRegistry());
        ctx.refresh();
    }

    configuration.setBeanFactory(ctx);
}

From source file:it.scoppelletti.programmerpower.console.spring.ConsoleApplicationRunner.java

/**
 * Inizializza il contesto dell&rsquo;applicazione.
 * /*from w ww  .j  a  v  a2 s. co m*/
 * @param  ui Interfaccia utente.
 * @return    Oggetto.
 */
private GenericApplicationContext initApplicationContext(UserInterfaceProvider ui) {
    SingletonBeanRegistry beanRegistry;
    GenericApplicationContext ctx = null;
    GenericApplicationContext applCtx;
    XmlBeanDefinitionReader reader;
    ConfigurableEnvironment env;
    PropertySource<?> propSource;
    MutablePropertySources propSources;

    try {
        ctx = new GenericApplicationContext();
        reader = new XmlBeanDefinitionReader(ctx);
        reader.loadBeanDefinitions(ConsoleApplicationRunner.CONSOLE_CONTEXT);
        reader.loadBeanDefinitions(initApplicationContextResourceName());

        beanRegistry = ctx.getBeanFactory();
        beanRegistry.registerSingleton(ConsoleApplicationRunner.BEAN_NAME, this);
        beanRegistry.registerSingleton(UserInterfaceProvider.BEAN_NAME, ui);

        env = ctx.getEnvironment();

        // Acquisisco gli eventuali profili configurati prima di aggiungere
        // quello di Programmer Power
        env.getActiveProfiles();

        env.addActiveProfile(ConsoleApplicationRunner.PROFILE);

        propSources = env.getPropertySources();

        propSources.addFirst(new ConsolePropertySource(ConsolePropertySource.class.getName(), this));

        propSource = BeanConfigUtils.loadPropertySource();
        if (propSource != null) {
            propSources.addFirst(propSource);
        }

        ctx.refresh();
        applCtx = ctx;
        ctx = null;
    } finally {
        if (ctx != null) {
            ctx.close();
            ctx = null;
        }
    }

    return applCtx;
}

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 ww.  j  a  va2s. c om*/

    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;
}