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:org.dspace.app.rest.utils.DSpaceConfigurationInitializer.java

@Override
public void initialize(final ConfigurableApplicationContext applicationContext) {
    // Load DSpace Configuration service (requires kernel already initialized)
    ConfigurationService configurationService = DSpaceServicesFactory.getInstance().getConfigurationService();
    Configuration configuration = configurationService.getConfiguration();

    // Create an Apache Commons Configuration Property Source from our configuration
    ConfigurationPropertySource apacheCommonsConfigPropertySource = new ConfigurationPropertySource(
            configuration.getClass().getName(), configuration);

    // Append it to the Environment's list of PropertySources
    applicationContext.getEnvironment().getPropertySources().addLast(apacheCommonsConfigPropertySource);
}

From source file:org.dspace.app.rest.utils.DSpaceKernelInitializer.java

@Override
public void initialize(final ConfigurableApplicationContext applicationContext) {
    // Check if the kernel is already started
    this.dspaceKernel = DSpaceKernelManager.getDefaultKernel();
    if (this.dspaceKernel == null) {
        DSpaceKernelImpl kernelImpl = null;
        try {//from w w  w. ja  va 2s .  c  o m
            // Load the kernel with default settings
            kernelImpl = DSpaceKernelInit.getKernel(null);
            if (!kernelImpl.isRunning()) {
                // Determine configured DSpace home & init the Kernel
                kernelImpl.start(getDSpaceHome(applicationContext.getEnvironment()));
            }
            this.dspaceKernel = kernelImpl;

        } catch (Exception e) {
            // failed to start so destroy it and log and throw an exception
            try {
                if (kernelImpl != null) {
                    kernelImpl.destroy();
                }
                this.dspaceKernel = null;
            } catch (Exception e1) {
                // nothing
            }
            String message = "Failure during ServletContext initialisation: " + e.getMessage();
            log.error(message, e);
            throw new RuntimeException(message, e);
        }
    }

    if (applicationContext.getParent() == null) {
        // Set the DSpace Kernel Application context as a parent of the Spring Boot context so that
        // we can auto-wire all DSpace Kernel services
        applicationContext.setParent(dspaceKernel.getServiceManager().getApplicationContext());

        //Add a listener for Spring Boot application shutdown so that we can nicely cleanup the DSpace kernel.
        applicationContext.addApplicationListener(new DSpaceKernelDestroyer(dspaceKernel));
    }
}

From source file:org.kuali.rice.core.web.util.PropertySources.java

/**
 * Register {@code propertySource} as the first thing Spring will check when looking up property
 * values.//  ww  w .j a  v a 2  s  . co m
 */
public static void addFirst(ConfigurableApplicationContext context, PropertySource<?> propertySource) {
    ConfigurableEnvironment env = context.getEnvironment();
    MutablePropertySources propertySources = env.getPropertySources();
    propertySources.addFirst(propertySource);
}

From source file:org.ojb.web.portal.WebPortalApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();

    Properties props = new Properties();
    String activeProfiles = "";

    try {//from www  . j a v a2s. co  m
        props.load(applicationContext.getClassLoader()
                .getResourceAsStream("config/ojb_web_external_resource.cfg"));
        activeProfiles = props.getProperty("spring.activeProfiles");
    } catch (IOException e) {
        LOG.info(
                "Unable to load spring profiles from external resource, will load default from ojb_web_portal.cfg");
    }

    if (StringUtils.isBlank(activeProfiles)) {
        try {
            props.clear();
            props.load(applicationContext.getClassLoader().getResourceAsStream("config/ojb-web-portal.cfg"));
            activeProfiles = props.getProperty("spring.activeProfiles");
        } catch (IOException e) {
            LOG.info("Unable to load spring profiles from ojb_web_portal.cfg");
        }
    }

    if (StringUtils.isBlank(activeProfiles)) {
        LOG.info("No spring profiles set, will run in 'standalone' mode");
        environment.setDefaultProfiles("standalone");
    } else {
        LOG.info("Setting default profiles to:" + activeProfiles);
        environment.setDefaultProfiles(activeProfiles.split(","));
    }
}

From source file:org.springframework.boot.context.initializer.FileEncodingApplicationContextInitializer.java

@Override
public void initialize(final ConfigurableApplicationContext context) {
    RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(context.getEnvironment(), "spring.");
    if (resolver.containsProperty("mandatoryFileEncoding")) {
        final String encoding = System.getProperty("file.encoding");
        final String desired = resolver.getProperty("mandatoryFileEncoding");
        if (encoding != null && !desired.equalsIgnoreCase(encoding)) {
            logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '"
                    + desired + "' (as defined in 'spring.mandatoryFileEncoding').");
            logger.error("Environment variable LANG is '" + System.getenv("LANG")
                    + "'. You could use a locale setting that matches encoding='" + desired + "'.");
            logger.error("Environment variable LC_ALL is '" + System.getenv("LC_ALL")
                    + "'. You could use a locale setting that matches encoding='" + desired + "'.");
            throw new IllegalStateException("The Java Virtual Machine has not "
                    + " been configured to use the desired default character encoding (" + desired + ").");
        }//www. ja  v a2s. c o m
    }
}

From source file:org.springframework.boot.context.initializer.LoggingApplicationContextInitializer.java

/**
 * Initialize the logging system according to preferences expressed through the
 * {@link Environment} and the classpath.
 *///from   w  ww .j  a  v a2  s.com
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    ConfigurableEnvironment environment = applicationContext.getEnvironment();

    if (this.parseArgs && this.springBootLogging == null) {
        if (environment.containsProperty("debug")) {
            this.springBootLogging = LogLevel.DEBUG;
        }
        if (environment.containsProperty("trace")) {
            this.springBootLogging = LogLevel.TRACE;
        }
    }

    for (Map.Entry<String, String> mapping : ENVIRONMENT_SYSTEM_PROPERTY_MAPPING.entrySet()) {
        if (environment.containsProperty(mapping.getKey())) {
            System.setProperty(mapping.getValue(), environment.getProperty(mapping.getKey()));
        }
    }

    LoggingSystem system = LoggingSystem.get(applicationContext.getClassLoader());

    // User specified configuration
    if (environment.containsProperty("logging.config")) {
        String value = environment.getProperty("logging.config");
        try {
            ResourceUtils.getURL(value).openStream().close();
            system.initialize(value);
            return;
        } catch (Exception ex) {
            // Swallow exception and continue
        }
        this.logger.warn("Logging environment value '" + value + "' cannot be opened and will be ignored");
    }

    system.initialize();
    if (this.springBootLogging != null) {
        initializeLogLevel(system, this.springBootLogging);
    }
}

From source file:org.springframework.boot.context.initializer.VcapApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    if (!environment.containsProperty(VCAP_APPLICATION) && !environment.containsProperty(VCAP_SERVICES)) {
        return;/*from  w  w w  . jav  a2 s.co m*/
    }

    Properties properties = new Properties();
    addWithPrefix(properties, getPropertiesFromApplication(environment), "vcap.application.");
    addWithPrefix(properties, getPropertiesFromServices(environment), "vcap.services.");
    MutablePropertySources propertySources = environment.getPropertySources();
    if (propertySources.contains(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME)) {
        propertySources.addAfter(CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME,
                new PropertiesPropertySource("vcap", properties));

    } else {
        propertySources.addFirst(new PropertiesPropertySource("vcap", properties));
    }

}

From source file:org.springframework.boot.SpringApplication.java

/**
 * Called to log active profile information.
 * @param context the application context
 *///from w  w  w .jav a  2  s. c om
protected void logStartupProfileInfo(ConfigurableApplicationContext context) {
    Log log = getApplicationLog();
    if (log.isInfoEnabled()) {
        String[] activeProfiles = context.getEnvironment().getActiveProfiles();
        if (ObjectUtils.isEmpty(activeProfiles)) {
            log.info("No profiles are active");
        } else {
            log.info("The following profiles are active: "
                    + StringUtils.arrayToCommaDelimitedString(activeProfiles));
        }
    }
}

From source file:org.springframework.cloud.bootstrap.config.ConfigServiceBootstrapConfiguration.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    CompositePropertySource composite = new CompositePropertySource("bootstrap");
    AnnotationAwareOrderComparator.sort(propertySourceLocators);
    boolean empty = true;
    for (PropertySourceLocator locator : propertySourceLocators) {
        PropertySource<?> source = null;
        try {/*w  ww .  jav a2s .  com*/
            source = locator.locate();
        } catch (Exception e) {
            logger.error("Could not locate PropertySource: " + e.getMessage());
        }
        if (source == null) {
            continue;
        }
        logger.info("Located property source: " + source);
        composite.addPropertySource(source);
        empty = false;
    }
    if (!empty) {
        MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
        if (propertySources.contains("bootstrap")) {
            propertySources.replace("bootstrap", composite);
        } else {
            propertySources.addFirst(composite);
        }
    }
}

From source file:org.springframework.cloud.bootstrap.config.PropertySourceBootstrapConfiguration.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    CompositePropertySource composite = new CompositePropertySource(BOOTSTRAP_PROPERTY_SOURCE_NAME);
    AnnotationAwareOrderComparator.sort(propertySourceLocators);
    boolean empty = true;
    for (PropertySourceLocator locator : propertySourceLocators) {
        PropertySource<?> source = null;
        try {//from w ww .  j a v a2  s . c om
            source = locator.locate(applicationContext.getEnvironment());
        } catch (Exception e) {
            logger.error("Could not locate PropertySource: " + e.getMessage());
        }
        if (source == null) {
            continue;
        }
        logger.info("Located property source: " + source);
        composite.addPropertySource(source);
        empty = false;
    }
    if (!empty) {
        MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
        if (propertySources.contains(BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
            propertySources.replace(BOOTSTRAP_PROPERTY_SOURCE_NAME, composite);
        } else {
            propertySources.addFirst(composite);
        }
    }
}