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.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    MapPropertySource decrypted = new MapPropertySource(DECRYPTED_PROPERTY_SOURCE_NAME,
            decrypt(environment.getPropertySources()));
    if (!decrypted.getSource().isEmpty()) {
        // We have some decrypted properties
        insert(environment.getPropertySources(), decrypted);
        ApplicationContext parent = applicationContext.getParent();
        if (parent != null && (parent.getEnvironment() instanceof ConfigurableEnvironment)) {
            ConfigurableEnvironment mutable = (ConfigurableEnvironment) parent.getEnvironment();
            // The parent is actually the bootstrap context, and it is fully
            // initialized, so we can fire an EnvironmentChangeEvent there to rebind
            // @ConfigurationProperties, in case they were encrypted.
            insert(mutable.getPropertySources(), decrypted);
            parent.publishEvent(new EnvironmentChangeEvent(decrypted.getSource().keySet()));
        }//from www  .  j a va  2s  .co m
    }
}

From source file:org.springframework.cloud.bootstrap.encrypt.EnvironmentDecryptApplicationListener.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    ConfigurableEnvironment environment = applicationContext.getEnvironment();
    Map<String, Object> overrides = new LinkedHashMap<String, Object>();
    for (PropertySource<?> source : environment.getPropertySources()) {
        decrypt(source, overrides);/*from   w  ww. ja v a  2 s .c  o  m*/
    }
    if (!overrides.isEmpty()) {
        environment.getPropertySources().addFirst(new MapPropertySource("decrypted", overrides));
    }
}

From source file:org.springframework.cloud.function.adapter.aws.SpringFunctionInitializer.java

@SuppressWarnings("unchecked")
protected void initialize() {
    if (!this.initialized.compareAndSet(false, true)) {
        return;// w w w .  j a  v  a 2  s . co  m
    }
    logger.info("Initializing: " + configurationClass);
    SpringApplicationBuilder builder = new SpringApplicationBuilder(configurationClass);
    ConfigurableApplicationContext context = builder.web(false).run();
    context.getAutowireCapableBeanFactory().autowireBean(this);
    String name = context.getEnvironment().getProperty("function.name");
    boolean defaultName = false;
    if (name == null) {
        name = "function";
        defaultName = true;
    }
    if (this.catalog == null) {
        this.function = context.getBean(name, Function.class);
    } else {
        this.function = this.catalog.lookupFunction(name);
        this.name = name;
        if (this.function == null) {
            if (defaultName) {
                name = "consumer";
            }
            this.consumer = this.catalog.lookupConsumer(name);
            this.name = name;
            if (this.consumer == null) {
                if (defaultName) {
                    name = "supplier";
                }
                this.supplier = this.catalog.lookupSupplier(name);
                this.name = name;
            }
        }
    }
    this.context = context;
}

From source file:org.springframework.test.context.support.AbstractContextLoader.java

/**
 * Prepare the {@link ConfigurableApplicationContext} created by this
 * {@code SmartContextLoader} <i>before</i> bean definitions are read.
 * <p>The default implementation:/*from w w w.  j av  a 2s  .  c o m*/
 * <ul>
 * <li>Sets the <em>active bean definition profiles</em> from the supplied
 * {@code MergedContextConfiguration} in the
 * {@link org.springframework.core.env.Environment Environment} of the
 * context.</li>
 * <li>Adds {@link PropertySource PropertySources} for all
 * {@linkplain MergedContextConfiguration#getPropertySourceLocations()
 * resource locations} and
 * {@linkplain MergedContextConfiguration#getPropertySourceProperties()
 * inlined properties} from the supplied {@code MergedContextConfiguration}
 * to the {@code Environment} of the context.</li>
 * <li>Determines what (if any) context initializer classes have been supplied
 * via the {@code MergedContextConfiguration} and instantiates and
 * {@linkplain ApplicationContextInitializer#initialize invokes} each with the
 * given application context.
 * <ul>
 * <li>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or annotated with {@link
 * org.springframework.core.annotation.Order @Order} will be sorted appropriately.</li>
 * </ul>
 * </li>
 * </ul>
 * @param context the newly created application context
 * @param mergedConfig the merged context configuration
 * @since 3.2
 * @see TestPropertySourceUtils#addPropertiesFilesToEnvironment
 * @see TestPropertySourceUtils#addInlinedPropertiesToEnvironment
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 * @see #loadContext(MergedContextConfiguration)
 * @see ConfigurableApplicationContext#setId
 */
protected void prepareContext(ConfigurableApplicationContext context, MergedContextConfiguration mergedConfig) {
    context.getEnvironment().setActiveProfiles(mergedConfig.getActiveProfiles());
    TestPropertySourceUtils.addPropertiesFilesToEnvironment(context, mergedConfig.getPropertySourceLocations());
    TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context,
            mergedConfig.getPropertySourceProperties());
    invokeApplicationContextInitializers(context, mergedConfig);
}

From source file:org.springframework.test.context.support.TestPropertySourceUtils.java

/**
 * Add the {@link Properties} files from the given resource {@code locations}
 * to the {@link Environment} of the supplied {@code context}.
 * <p>This method simply delegates to
 * {@link #addPropertiesFilesToEnvironment(ConfigurableEnvironment, ResourceLoader, String...)}.
 * @param context the application context whose environment should be updated;
 * never {@code null}/*from   w  w  w . j  a v  a  2 s .  c om*/
 * @param locations the resource locations of {@code Properties} files to add
 * to the environment; potentially empty but never {@code null}
 * @since 4.1.5
 * @see ResourcePropertySource
 * @see TestPropertySource#locations
 * @see #addPropertiesFilesToEnvironment(ConfigurableEnvironment, ResourceLoader, String...)
 * @throws IllegalStateException if an error occurs while processing a properties file
 */
public static void addPropertiesFilesToEnvironment(ConfigurableApplicationContext context,
        String... locations) {
    Assert.notNull(context, "'context' must not be null");
    Assert.notNull(locations, "'locations' must not be null");
    addPropertiesFilesToEnvironment(context.getEnvironment(), context, locations);
}

From source file:org.springframework.test.context.support.TestPropertySourceUtils.java

/**
 * Add the given <em>inlined properties</em> to the {@link Environment} of the
 * supplied {@code context}.//from   w  ww  . ja v a2  s .  co  m
 * <p>This method simply delegates to
 * {@link #addInlinedPropertiesToEnvironment(ConfigurableEnvironment, String[])}.
 * @param context the application context whose environment should be updated;
 * never {@code null}
 * @param inlinedProperties the inlined properties to add to the environment;
 * potentially empty but never {@code null}
 * @since 4.1.5
 * @see TestPropertySource#properties
 * @see #addInlinedPropertiesToEnvironment(ConfigurableEnvironment, String[])
 */
public static void addInlinedPropertiesToEnvironment(ConfigurableApplicationContext context,
        String... inlinedProperties) {
    Assert.notNull(context, "'context' must not be null");
    Assert.notNull(inlinedProperties, "'inlinedProperties' must not be null");
    addInlinedPropertiesToEnvironment(context.getEnvironment(), inlinedProperties);
}

From source file:org.springframework.xd.dirt.plugins.spark.streaming.SparkStreamingPlugin.java

@Override
public void postProcessModule(Module module) {
    ConfigurableApplicationContext moduleContext = module.getApplicationContext();
    ConfigurableEnvironment env = moduleContext.getEnvironment();
    String transport = env.getProperty("XD_TRANSPORT");
    Properties messageBusProperties = getMessageBusProperties(module);
    Properties inboundModuleProperties = this.extractConsumerProducerProperties(module)[0];
    Properties outboundModuleProperties = this.extractConsumerProducerProperties(module)[1];
    String defaultStorageLevel = env.getProperty(SparkStreamingSupport.SPARK_STORAGE_LEVEL_PROP);
    StorageLevel configuredStorageLevel = StorageLevel
            .fromString(StringUtils.hasText(defaultStorageLevel) ? defaultStorageLevel
                    : SparkStreamingSupport.SPARK_DEFAULT_STORAGE_LEVEL);
    String storageLevelFromModule = module.getProperties()
            .getProperty(SparkStreamingSupport.SPARK_STORAGE_LEVEL_MODULE_OPTION);
    StorageLevel storageLevel = StringUtils.hasText(storageLevelFromModule)
            ? StorageLevel.fromString(storageLevelFromModule)
            : configuredStorageLevel;/*  www  .ja  v a2  s .  c om*/
    MessageBusReceiver receiver = null;
    if (transport.equals("local")) {
        SparkStreamingSupport processor;
        Properties sparkConfigs = null;
        try {
            processor = module.getComponent(SparkStreamingSupport.class);
            Assert.notNull(processor,
                    "Problem getting the spark streaming module. Is the module context active?");
            sparkConfigs = getSparkModuleProperties(processor);
        } catch (NoSuchBeanDefinitionException e) {
            throw new IllegalStateException("Either java or scala module should be present.");
        }
        String sparkMasterUrl = env.getProperty(SparkStreamingSupport.SPARK_MASTER_URL_PROP);
        if (sparkConfigs != null
                && StringUtils.hasText(sparkConfigs.getProperty(SparkStreamingSupport.SPARK_MASTER_URL_PROP))) {
            sparkMasterUrl = sparkConfigs.getProperty(SparkStreamingSupport.SPARK_MASTER_URL_PROP);
        }
        Assert.notNull(sparkMasterUrl, "Spark Master URL must be set.");
        if (!sparkMasterUrl.startsWith("local")) {
            throw new IllegalStateException("Spark cluster mode must be 'local' for 'local' XD transport.");
        }
        LocalMessageBusHolder messageBusHolder = new LocalMessageBusHolder();
        LocalMessageBusHolder.set(module.getComponent(MessageBus.class));
        receiver = new MessageBusReceiver(messageBusHolder, storageLevel, messageBusProperties,
                inboundModuleProperties, ModuleTypeConversionSupport.getInputMimeType(module));
        if (module.getType().equals(ModuleType.processor)) {
            MessageBusSender sender = new MessageBusSender(messageBusHolder, getOutputChannelName(module),
                    buildTapChannelName(module), messageBusProperties, outboundModuleProperties,
                    ModuleTypeConversionSupport.getOutputMimeType(module), module.getProperties());
            ConfigurableBeanFactory beanFactory = module.getApplicationContext().getBeanFactory();
            beanFactory.registerSingleton("messageBusSender", sender);
        }
    } else {
        receiver = new MessageBusReceiver(storageLevel, messageBusProperties, inboundModuleProperties,
                ModuleTypeConversionSupport.getInputMimeType(module));
        if (module.getType().equals(ModuleType.processor)) {
            ConfigurableBeanFactory beanFactory = module.getApplicationContext().getBeanFactory();
            MessageBusSender sender = new MessageBusSender(getOutputChannelName(module),
                    buildTapChannelName(module), messageBusProperties, outboundModuleProperties,
                    ModuleTypeConversionSupport.getOutputMimeType(module), module.getProperties());
            beanFactory.registerSingleton("messageBusSender", sender);
        }
    }
    registerMessageBusReceiver(receiver, module);

    // This used to be in SSDModule.start
    try {
        SparkStreamingSupport processor = module.getComponent(SparkStreamingSupport.class);
        Assert.notNull(processor, "Problem getting the spark streaming module. Is the module context active?");
        Properties sparkConfigs = getSparkModuleProperties(processor);
        startSparkStreamingContext(sparkConfigs, processor, module);
    } catch (NoSuchBeanDefinitionException e) {
        throw new IllegalStateException("Either java or scala module should be present.");
    }

}

From source file:org.springframework.xd.dirt.plugins.stream.StreamPlugin.java

@Override
public void preProcessSharedContext(ConfigurableApplicationContext context) {
    context.addBeanFactoryPostProcessor(new BeanDefinitionAddingPostProcessor(context.getEnvironment(),
            new ClassPathResource(MESSAGE_BUS)));
}

From source file:org.springframework.xd.module.AbstractPlugin.java

private void addBeanFactoryPostProcessors(ConfigurableApplicationContext context, String... paths) {
    for (String path : paths) {
        context.addBeanFactoryPostProcessor(
                new BeanDefinitionAddingPostProcessor(context.getEnvironment(), new ClassPathResource(path)));
    }/*from  w ww.j a  va  2 s .c  o m*/
}