Example usage for org.springframework.context ConfigurableApplicationContext getEnvironment

List of usage examples for org.springframework.context ConfigurableApplicationContext getEnvironment

Introduction

In this page you can find the example usage for org.springframework.context ConfigurableApplicationContext getEnvironment.

Prototype

@Override
ConfigurableEnvironment getEnvironment();

Source Link

Document

Return the Environment for this application context in configurable form, allowing for further customization.

Usage

From source file:net.community.chest.gitcloud.facade.AbstractContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    MutablePropertySources propSources = environment.getPropertySources();
    ExtendedPlaceholderResolver sourcesResolver = ExtendedPlaceholderResolverUtils
            .toPlaceholderResolver(propSources);
    File appBase = resolveApplicationBase(propSources, sourcesResolver);
    File configFile = getApplicationConfigFile(appBase, sourcesResolver);
    Collection<String> activeProfiles = resolveActiveProfiles(sourcesResolver);
    if (ExtendedCollectionUtils.size(activeProfiles) > 0) {
        environment.setActiveProfiles(activeProfiles.toArray(new String[activeProfiles.size()]));
    }/*  www .ja  v  a  2 s  .  co m*/

    try {
        ensureFoldersExistence(appBase, configFile, sourcesResolver);
    } catch (IOException e) {
        logger.error("ensureFoldersExistence(" + ExtendedFileUtils.toString(appBase) + ")" + " "
                + e.getClass().getSimpleName() + ": " + e.getMessage());
    }

    if (logger.isDebugEnabled()) {
        showArtifactsVersions();
    }
}

From source file:me.j360.boot.standard.test.SessionRedisApplicationTests.java

@Test
public void sessionExpiry() throws Exception {

    String port = null;//from ww w  .  j av a  2s.c om

    try {
        ConfigurableApplicationContext context = new SpringApplicationBuilder().sources(J360Configuration.class)
                .properties("server.port:0").initializers(new ServerPortInfoApplicationContextInitializer())
                .run();
        port = context.getEnvironment().getProperty("local.server.port");
    } catch (RuntimeException ex) {
        if (!redisServerRunning(ex)) {
            return;
        }
    }

    URI uri = URI.create("http://localhost:" + port + "/");
    RestTemplate restTemplate = new RestTemplate();

    ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
    String uuid1 = response.getBody();
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Cookie", response.getHeaders().getFirst("Set-Cookie"));

    RequestEntity<Void> request = new RequestEntity<Void>(requestHeaders, HttpMethod.GET, uri);

    String uuid2 = restTemplate.exchange(request, String.class).getBody();
    assertThat(uuid1, is(equalTo(uuid2)));

    Thread.sleep(5000);

    String uuid3 = restTemplate.exchange(request, String.class).getBody();
    assertThat(uuid2, is(not(equalTo(uuid3))));
}

From source file:org.springbyexample.contact.web.context.ContactApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    String springProfilesActive = System.getProperty(SPRING_PROFILES_ACTIVE_PROPERTY);

    if (StringUtils.hasText(springProfilesActive)) {
        logger.info("Using set spring profiles.  profiles='{}'", springProfilesActive);
    } else {//from   w  ww  . j ava  2  s  . co m
        applicationContext.getEnvironment().setActiveProfiles(DEFAULT_ACTIVE_PROFILES);

        logger.info("Setting default spring profiles.  profiles='{}'", DEFAULT_ACTIVE_PROFILES);
    }
}

From source file:com.devnexus.ting.web.config.DefaultApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    final CloudEnvironment env = new CloudEnvironment();
    if (env.getInstanceInfo() != null) {
        LOGGER.info("cloud API: " + env.getCloudApiUri());
        applicationContext.getEnvironment().setActiveProfiles("cloud",
                SpringContextMode.DemoContextConfiguration.getCode());
    } else {/*from   w  w  w . j  a v a2  s.com*/
        final String profile = System.getProperty("ting-spring-profile");

        if (profile == null) {
            LOGGER.info("System property 'ting-spring-profile' not set. Setting active profile to '{}'.",
                    SpringContextMode.DemoContextConfiguration.getCode());
            applicationContext.getEnvironment()
                    .setActiveProfiles(SpringContextMode.DemoContextConfiguration.getCode());
        } else {
            applicationContext.getEnvironment().setActiveProfiles(profile);
        }
    }

    final ConfigurableEnvironment environment = applicationContext.getEnvironment();

    if (environment.acceptsProfiles(SpringProfile.STANDALONE)) {
        final String tingHome = environment.getProperty(Apphome.APP_HOME_DIRECTORY);
        final ResourcePropertySource propertySource;
        final String productionPropertySourceLocation = "file:" + tingHome + File.separator
                + SystemInformationUtils.TING_CONFIG_FILENAME;
        try {
            propertySource = new ResourcePropertySource(productionPropertySourceLocation);
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Unable to get ResourcePropertySource '" + productionPropertySourceLocation + "'", e);
        }
        environment.getPropertySources().addFirst(propertySource);
        LOGGER.info("Properties for standalone mode loaded [" + productionPropertySourceLocation + "]");
    } else {
        final String demoPropertySourceLocation = "classpath:ting-demo.properties";
        final ResourcePropertySource propertySource;
        try {
            propertySource = new ResourcePropertySource(demoPropertySourceLocation);
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Unable to get ResourcePropertySource '" + demoPropertySourceLocation + "'", e);
        }
        environment.getPropertySources().addFirst(propertySource);
        LOGGER.info("Properties for demo mode loaded [" + demoPropertySourceLocation + "]");
    }

    final boolean mailEnabled = environment.getProperty("mail.enabled", Boolean.class, Boolean.FALSE);
    final boolean twitterEnabled = environment.getProperty("twitter.enabled", Boolean.class, Boolean.FALSE);
    final boolean websocketEnabled = environment.getProperty("websocket.enabled", Boolean.class, Boolean.FALSE);

    if (mailEnabled) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.MAIL_ENABLED);
    }
    if (twitterEnabled) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.TWITTER_ENABLED);
    }
    if (websocketEnabled) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.WEBSOCKET_ENABLED);
    }

}

From source file:com.netflix.spinnaker.fiat.YamlFileApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    try {/*from  ww  w .jav a2s .  c  o  m*/
        Resource resource = applicationContext.getResource("classpath:application.yml");
        YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
        PropertySource<?> yamlTestProperties = sourceLoader.load("yamlTestProperties", resource, null);
        applicationContext.getEnvironment().getPropertySources().addLast(yamlTestProperties);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:io.pivotal.springcloud.ssl.CloudFoundryCertificateTruster.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    if (!inited) {
        inited = true;//from  w  w  w. j  a  v a2 s .  c om
        String trustCertUrls = null;
        String trustStore = null;
        String trustStorePassword = null;

        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        for (PropertySource<?> propertySource : environment.getPropertySources()) {
            if (propertySource.containsProperty("app.ssl.trustStore"))
                trustStore = (String) propertySource.getProperty("app.ssl.trustStore");
            if (propertySource.containsProperty("app.ssl.trustStorePassword"))
                trustStorePassword = (String) propertySource.getProperty("app.ssl.trustStorePassword");
            if (propertySource.containsProperty("app.ssl.trustCertUrls"))
                trustCertUrls = (String) propertySource.getProperty("app.ssl.trustCertUrls");
        }

        if (trustCertUrls != null)
            trustCertificatesFromURLInternal(trustCertUrls);

        if (trustStore != null)
            trustCertificatesFromStoreInternal(applicationContext, trustStore, trustStorePassword);
    }
}

From source file:org.openwms.core.startup.ApplicationInitializer.java

/**
 * {@inheritDoc}//w  w w  .  j  a v a 2s.co  m
 * 
 * Depending on the underlying platform, different Spring profiles are
 * included.
 */
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    String activeProfile = System.getProperty("spring.profiles.active");
    if ("OSGI".equalsIgnoreCase(activeProfile)) {
        LOGGER.info("Running in OSGI environment");
    } else if ("noOSGI".equalsIgnoreCase(activeProfile)) {
        LOGGER.info("Running in a non-OSGI environment");
    } else {
        applicationContext.getEnvironment().setActiveProfiles("noOSGI");
        applicationContext.refresh();
        LOGGER.info("Switched to a non-OSGI environment");
    }
}

From source file:org.springsource.investigation.ReproTests.java

@SuppressWarnings("unchecked")
@Test//  w  w  w  .  java 2 s. c o m
public void repro() {
    ConfigurableApplicationContext parent = new GenericApplicationContext();
    parent.refresh();

    AnnotationConfigApplicationContext child = new AnnotationConfigApplicationContext();
    child.setParent(parent);
    child.refresh();

    ConfigurableEnvironment env = child.getBean(ConfigurableEnvironment.class);
    assertThat("UNKNOWN ENV", env,
            anyOf(sameInstance(parent.getEnvironment()), sameInstance(child.getEnvironment())));
    assertThat("EXPECTED CHILD CTX ENV", env, sameInstance(child.getEnvironment()));
}

From source file:eu.freme.broker.integration_tests.EServiceTest.java

/**
 * This method creates and authenticats two users, userwithpermission and userwithoutpermission.
 * Furthermore the admin token is created.
 * @throws UnirestException/*from  w  w  w .j  a v a2  s . c  o m*/
 */
private void authenticateUsers() throws UnirestException {
    //Creates two users, one intended to have permission, the other not
    createUser(usernameWithPermission, passwordWithPermission);
    tokenWithPermission = authenticateUser(usernameWithPermission, passwordWithPermission);
    createUser(usernameWithoutPermission, passwordWithoutPermission);
    tokenWithOutPermission = authenticateUser(usernameWithoutPermission, passwordWithoutPermission);
    ConfigurableApplicationContext context = IntegrationTestSetup.getApplicationContext();
    tokenAdmin = authenticateUser(context.getEnvironment().getProperty("admin.username"),
            context.getEnvironment().getProperty("admin.password"));
    authenticated = true;
}

From source file:com.devnexus.ting.DefaultApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    final CloudEnvironment env = new CloudEnvironment();
    if (env.getInstanceInfo() != null) {
        LOGGER.info("Running in the cloud - API: " + env.getCloudApiUri());
        applicationContext.getEnvironment().setActiveProfiles(SpringProfile.CLOUD);
    } else {/*w  ww .j ava2s  .  c om*/

        final Apphome apphome = SystemInformationUtils.retrieveBasicSystemInformation();
        SpringContextMode springContextMode;

        LOGGER.info("DevNexus Apphome: " + apphome);

        if (SystemInformationUtils.existsConfigFile(apphome.getAppHomePath())) {
            springContextMode = SpringContextMode.ProductionContextConfiguration;
        } else {
            springContextMode = SpringContextMode.DemoContextConfiguration;
        }

        applicationContext.getEnvironment().setActiveProfiles(springContextMode.getCode());
    }

    final ConfigurableEnvironment environment = applicationContext.getEnvironment();

    if (environment.acceptsProfiles(SpringProfile.STANDALONE)) {
        final String tingHome = environment.getProperty(Apphome.APP_HOME_DIRECTORY);
        final PropertySource<?> propertySource;
        final YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();

        final String productionPropertySourceLocation;
        final Apphome apphome = SystemInformationUtils.retrieveBasicSystemInformation();
        if (apphome.getAppHomeSource() == AppHomeSource.USER_DIRECTORY) {
            productionPropertySourceLocation = "file:" + apphome.getAppHomePath() + File.separator
                    + SystemInformationUtils.TING_CONFIG_FILENAME;
        } else {
            productionPropertySourceLocation = "file:" + tingHome + File.separator
                    + SystemInformationUtils.TING_CONFIG_FILENAME;
        }

        try {
            propertySource = yamlPropertySourceLoader.load("devnexus-standalone",
                    new DefaultResourceLoader().getResource(productionPropertySourceLocation), null);
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Unable to get ResourcePropertySource '" + productionPropertySourceLocation + "'", e);
        }
        environment.getPropertySources().addFirst(propertySource);
        LOGGER.info("Properties for standalone mode loaded [" + productionPropertySourceLocation + "].");
    } else {
        LOGGER.info("Using Properties for demo mode.");
    }

    final String emailProviderAsString = environment.getProperty("devnexus.mail.emailProvider");
    final EmailProvider emailProvider = EmailProvider.valueOf(emailProviderAsString.trim().toUpperCase());
    final boolean twitterEnabled = environment.getProperty("devnexus.twitter.enabled", Boolean.class,
            Boolean.FALSE);
    final boolean websocketEnabled = environment.getProperty("devnexus.websocket.enabled", Boolean.class,
            Boolean.FALSE);
    final boolean payPalEnabled = environment.containsProperty("PAYPAL_MODE");

    LOGGER.info("Uses Settings:" + "\nEmail Provider: " + emailProvider + "\nTwitter Enabled: " + twitterEnabled
            + "\nPayPal Enabled: " + payPalEnabled + "\nWebsocket Enabled: " + websocketEnabled);

    if (EmailProvider.SENDGRID.equals(emailProvider)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.SENDGRID_ENABLED);
    } else if (EmailProvider.SMTP.equals(emailProvider)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.SMTP_ENABLED);
    } else if (EmailProvider.AMAZON_SES.equals(emailProvider)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.AMAZON_SES_ENABLED);
    } else if (EmailProvider.NONE.equals(emailProvider)) {
    } else {
        throw new IllegalArgumentException("Unknown EmailProvider: " + emailProvider);
    }

    if (!EmailProvider.NONE.equals(emailProvider)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.MAIL_ENABLED);
    }

    if (twitterEnabled) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.TWITTER_ENABLED);
    }
    if (websocketEnabled) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.WEBSOCKET_ENABLED);
    }
    if (payPalEnabled) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_ENABLED);
        switch (environment.getProperty("PAYPAL_MODE")) {
        case "live":
            applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_LIVE);
            break;
        default:
            applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_SANDBOX);
            break;
        }
    }
    if (environment.getProperty("DEVELOPMENT_MODE", Boolean.class, Boolean.FALSE)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.DEVELOPMENT_ENABLED);
    }
}