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:com.jaspersoft.jasperserver.export.BaseExportImportCommand.java

protected ConfigurableApplicationContext createSpringContext(Parameters exportParameters,
        String resourceFileName) throws IOException {
    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader configReader = new XmlBeanDefinitionReader(ctx);
    Resource[] resources = ctx.getResources(resourceFileName);
    commandOut.info("First resource path:" + resources[0].getFile().getAbsolutePath());
    Arrays.sort(resources, new ResourceComparator());
    commandOut.info("Started to load resources");
    for (Resource resource : resources) {
        commandOut.info("Resource name: " + resource.getFilename());
        configReader.loadBeanDefinitions(resource);
    }/*from   w  w  w  .  j  av a  2s  . c o m*/
    ctx.refresh();
    return ctx;
}

From source file:atunit.spring.SpringContainer.java

public Object createTest(Class<?> testClass, Map<Field, Object> fieldValues) throws Exception {

    GenericApplicationContext ctx = new GenericApplicationContext();

    for (Field field : fieldValues.keySet()) {

        Bean beanAnno = field.getAnnotation(Bean.class);

        AbstractBeanDefinition beandef = defineInstanceHolderFactoryBean(field.getType(),
                fieldValues.get(field));

        if ((beanAnno != null) && !beanAnno.value().equals("")) {
            ctx.registerBeanDefinition(beanAnno.value(), beandef);
        } else {/*from  ww  w .ja  va 2  s .co  m*/
            BeanDefinitionReaderUtils.registerWithGeneratedName(beandef, ctx);
        }
    }

    loadBeanDefinitions(testClass, ctx);

    fillInMissingFieldBeans(testClass, ctx);

    ctx.refresh();

    Object test = testClass.newInstance();
    for (Field field : testClass.getDeclaredFields()) {
        field.setAccessible(true);
        Bean beanAnno = field.getAnnotation(Bean.class);
        if (beanAnno == null) {
            if (fieldValues.containsKey(field)) {
                field.set(test, fieldValues.get(field));
            }
        } else {
            if (!beanAnno.value().equals("")) {
                field.set(test, ctx.getBean(beanAnno.value()));
            } else {
                String[] beanNames = ctx.getBeanNamesForType(field.getType());
                if (beanNames.length < 1) {
                    throw new BeanCreationException("There are no beans defined with type " + field.getType());
                }
                if (beanNames.length > 1) {
                    throw new BeanCreationException(
                            "There are " + beanNames.length + " beans defined with type " + field.getType()
                                    + "; consider wiring by name instead");
                }
                field.set(test, ctx.getBean(beanNames[0]));
            }
        }
    }

    return test;
}

From source file:com.obergner.hzserver.Main.java

void start() throws Exception {
    enableHangupSupport();/*w  w w . j a va  2s  .c  o  m*/

    this.serverInfo.logBootStart();

    final GenericApplicationContext ctx = new GenericApplicationContext();
    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions("classpath:META-INF/spring/hz-server-main-context.xml",
            "classpath*:META-INF/spring/hz-cache-context.xml");
    ctx.registerShutdownHook();
    ctx.addApplicationListener(new ApplicationListener<ContextRefreshedEvent>() {

        @Override
        public void onApplicationEvent(final ContextRefreshedEvent event) {
            Main.this.serverInfo.logBootCompleted();

        }
    });
    ctx.addApplicationListener(new ApplicationListener<ContextStoppedEvent>() {

        @Override
        public void onApplicationEvent(final ContextStoppedEvent event) {
            Main.this.serverInfo.logShutdownCompleted();
        }
    });
    ctx.refresh();
}

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 {//from w w w .j  av  a  2s .  co 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.bstek.dorado.core.SpringApplicationContext.java

/**
 * Dorado EngineApplicationContext// w w  w.  j  av  a 2  s  .c  o  m
 * 
 * @throws Exception
 */
@Override
public ApplicationContext getApplicationContext() throws Exception {
    if (applicationContext == null) {
        GenericApplicationContext ctx = internalCreateApplicationContext();
        applicationContext = ctx;

        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);

        String configLocation = Configure.getString(CONFIG_PROPERTY);
        if (StringUtils.isBlank(configLocation)) {
            throw new IllegalArgumentException("[" + CONFIG_PROPERTY + "] undefined.");
        }

        for (Resource resource : getConfigLocations(configLocation)) {
            loadBeanDefintiionsFromResource(xmlReader, resource);
        }

        String extConfigLocation = Configure.getString(EXT_CONFIG_PROPERTY);
        if (!StringUtils.isBlank(extConfigLocation)) {
            for (Resource resource : getConfigLocations(extConfigLocation)) {
                loadBeanDefintiionsFromResource(xmlReader, resource);
            }
        }

        ctx.refresh();
    }
    return applicationContext;
}

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

@Override
public ApplicationContext resolveSiteWhereContext(IVersion version) throws SiteWhereException {
    LOGGER.info("Loading Spring configuration ...");
    File sitewhereConf = getSiteWhereConfigFolder();
    File serverConfigFile = new File(sitewhereConf, SERVER_CONFIG_FILE_NAME);
    if (!serverConfigFile.exists()) {
        throw new SiteWhereException(
                "SiteWhere server configuration not found: " + serverConfigFile.getAbsolutePath());
    }/*from  w ww.  j  a  v  a 2 s  .  com*/
    GenericApplicationContext context = new GenericApplicationContext();

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

    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(serverConfigFile));

    context.refresh();
    return context;
}

From source file:org.alfresco.util.bean.DynamicContextLoader.java

/**
 * Iterates through the list of ContextLoaderEvaluators and loads the additional
 * contexts if appropriate.// w  ww.ja v  a  2s  .  com
 */
public void init() {
    GenericApplicationContext childContext = new GenericApplicationContext(applicationContext);
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(childContext);
    boolean isContextChanged = false;
    for (ContextLoaderEvaluator contextLoaderEvaluator : contextLoaderEvaluators) {
        if (contextLoaderEvaluator.loadContext()) {
            if (logger.isInfoEnabled()) {
                logger.info(
                        "Loading dynamic context: " + contextLoaderEvaluator.getContextResource().toString());
            }
            xmlReader.loadBeanDefinitions(contextLoaderEvaluator.getContextResource());
            isContextChanged = true;
        } else {
            if (logger.isInfoEnabled()) {
                logger.info(
                        "Skipping dynamic context: " + contextLoaderEvaluator.getContextResource().toString());
            }
        }
    }
    if (isContextChanged) {
        childContext.refresh();
    }
}

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

/**
 * Creates the application context./*w  w  w. ja v  a  2  s .  co m*/
 * 
 * @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: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();
    return context;
}

From source file:org.springframework.cloud.aws.context.config.xml.ContextCredentialsBeanDefinitionParserTest.java

@Test
public void parseBean_withProfileCredentialsProviderAndProfileFile_createProfileCredentialsProvider()
        throws IOException {
    GenericApplicationContext applicationContext = new GenericApplicationContext();

    Map<String, Object> secretAndAccessKeyMap = new HashMap<>();
    secretAndAccessKeyMap.put("profilePath",
            new ClassPathResource(getClass().getSimpleName() + "-profile", getClass()).getFile()
                    .getAbsolutePath());

    applicationContext.getEnvironment().getPropertySources()
            .addLast(new MapPropertySource("test", secretAndAccessKeyMap));
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setPropertySources(applicationContext.getEnvironment().getPropertySources());

    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(applicationContext);
    reader.loadBeanDefinitions(new ClassPathResource(
            getClass().getSimpleName() + "-profileCredentialsProviderWithFile.xml", getClass()));

    applicationContext.refresh();

    AWSCredentialsProvider provider = applicationContext.getBean(
            AmazonWebserviceClientConfigurationUtils.CREDENTIALS_PROVIDER_BEAN_NAME,
            AWSCredentialsProvider.class);
    assertNotNull(provider);/*from w ww.  jav  a  2s .  com*/

    assertEquals("testAccessKey", provider.getCredentials().getAWSAccessKeyId());
    assertEquals("testSecretKey", provider.getCredentials().getAWSSecretKey());
}