Search in sources :

Example 81 with Environment

use of org.springframework.core.env.Environment in project spring-cloud-stream by spring-cloud.

the class MessageConverterConfigurer method configureMessageChannel.

/**
 * Setup data-type and message converters for the given message channel.
 * @param channel message channel to set the data-type and message converters
 * @param channelName the channel name
 * @param inbound inbound (i.e., "input") or outbound channel
 */
private void configureMessageChannel(MessageChannel channel, String channelName, boolean inbound) {
    Assert.isAssignable(AbstractMessageChannel.class, channel.getClass());
    AbstractMessageChannel messageChannel = (AbstractMessageChannel) channel;
    BindingProperties bindingProperties = this.bindingServiceProperties.getBindingProperties(channelName);
    String contentType = bindingProperties.getContentType();
    ProducerProperties producerProperties = bindingProperties.getProducer();
    boolean partitioned = !inbound && producerProperties != null && producerProperties.isPartitioned();
    boolean functional = streamFunctionProperties != null && (StringUtils.hasText(streamFunctionProperties.getDefinition()) || StringUtils.hasText(bindingServiceProperties.getInputBindings()) || StringUtils.hasText(bindingServiceProperties.getOutputBindings()));
    if (partitioned) {
        if (inbound || !functional) {
            messageChannel.addInterceptor(new PartitioningInterceptor(bindingProperties));
        }
    }
    Environment environment = this.beanFactory == null ? null : this.beanFactory.getBean(Environment.class);
    ConsumerProperties consumerProperties = bindingProperties.getConsumer();
    if (this.isNativeEncodingNotSet(producerProperties, consumerProperties, inbound)) {
        if (inbound) {
            messageChannel.addInterceptor(new InboundContentTypeEnhancingInterceptor(contentType));
        } else {
            if (environment != null && environment.containsProperty("spring.cloud.stream.rabbit.bindings." + channelName + ".producer.routing-key-expression")) {
                this.setSkipOutputConversionIfNecessary();
                functional = false;
            }
            if (!functional) {
                messageChannel.addInterceptor(new OutboundContentTypeConvertingInterceptor(contentType, this.compositeMessageConverter));
            }
        }
    }
}
Also used : ProducerProperties(org.springframework.cloud.stream.binder.ProducerProperties) AbstractMessageChannel(org.springframework.integration.channel.AbstractMessageChannel) BindingProperties(org.springframework.cloud.stream.config.BindingProperties) Environment(org.springframework.core.env.Environment) ConsumerProperties(org.springframework.cloud.stream.binder.ConsumerProperties)

Example 82 with Environment

use of org.springframework.core.env.Environment in project cas by apereo.

the class CasCoreBootstrapStandaloneConfiguration method loadSettingsFromConfigurationSources.

private void loadSettingsFromConfigurationSources(final Environment environment, final Properties props, final File config) {
    final List<String> profiles = new ArrayList<>();
    profiles.add(configurationPropertiesEnvironmentManager().getApplicationName());
    profiles.addAll(Arrays.stream(environment.getActiveProfiles()).collect(Collectors.toList()));
    final String propertyNames = profiles.stream().collect(Collectors.joining("|"));
    final String regex = String.format("(%s|application)\\.(yml|properties)", propertyNames);
    LOGGER.debug("Looking for configuration files at [{}] that match the pattern [{}]", config, regex);
    final Collection<File> configFiles = FileUtils.listFiles(config, new RegexFileFilter(regex, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE).stream().sorted(Comparator.comparing(File::getName)).collect(Collectors.toList());
    LOGGER.info("Configuration files found at [{}] are [{}]", config, configFiles);
    configFiles.forEach(Unchecked.consumer(f -> {
        LOGGER.debug("Loading configuration file [{}]", f);
        if (f.getName().toLowerCase().endsWith("yml")) {
            final Map pp = loadYamlProperties(new FileSystemResource(f));
            LOGGER.debug("Found settings [{}] in YAML file [{}]", pp.keySet(), f);
            props.putAll(pp);
        } else {
            final Properties pp = new Properties();
            pp.load(new FileReader(f));
            LOGGER.debug("Found settings [{}] in file [{}]", pp.keySet(), f);
            props.putAll(pp);
        }
    }));
}
Also used : Arrays(java.util.Arrays) IOCase(org.apache.commons.io.IOCase) PropertySource(org.springframework.core.env.PropertySource) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) ArrayList(java.util.ArrayList) Map(java.util.Map) CasConfigurationPropertiesEnvironmentManager(org.apereo.cas.configuration.CasConfigurationPropertiesEnvironmentManager) ConditionalOnProperty(org.springframework.boot.autoconfigure.condition.ConditionalOnProperty) TrueFileFilter(org.apache.commons.io.filefilter.TrueFileFilter) RegexFileFilter(org.apache.commons.io.filefilter.RegexFileFilter) Resource(org.springframework.core.io.Resource) Unchecked(org.jooq.lambda.Unchecked) Logger(org.slf4j.Logger) ResourceLoader(org.springframework.core.io.ResourceLoader) Properties(java.util.Properties) Collection(java.util.Collection) PropertiesPropertySource(org.springframework.core.env.PropertiesPropertySource) FileSystemResource(org.springframework.core.io.FileSystemResource) FileUtils(org.apache.commons.io.FileUtils) Profile(org.springframework.context.annotation.Profile) Collectors(java.util.stream.Collectors) File(java.io.File) YamlPropertiesFactoryBean(org.springframework.beans.factory.config.YamlPropertiesFactoryBean) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) Environment(org.springframework.core.env.Environment) Bean(org.springframework.context.annotation.Bean) FileReader(java.io.FileReader) Comparator(java.util.Comparator) YamlProcessor(org.springframework.beans.factory.config.YamlProcessor) PropertySourceLocator(org.springframework.cloud.bootstrap.config.PropertySourceLocator) ArrayList(java.util.ArrayList) RegexFileFilter(org.apache.commons.io.filefilter.RegexFileFilter) FileReader(java.io.FileReader) FileSystemResource(org.springframework.core.io.FileSystemResource) Properties(java.util.Properties) File(java.io.File) Map(java.util.Map)

Example 83 with Environment

use of org.springframework.core.env.Environment in project spring-framework by spring-projects.

the class PropertySourcesPlaceholderConfigurer method postProcessBeanFactory.

/**
	 * {@inheritDoc}
	 * <p>Processing occurs by replacing ${...} placeholders in bean definitions by resolving each
	 * against this configurer's set of {@link PropertySources}, which includes:
	 * <ul>
	 * <li>all {@linkplain org.springframework.core.env.ConfigurableEnvironment#getPropertySources
	 * environment property sources}, if an {@code Environment} {@linkplain #setEnvironment is present}
	 * <li>{@linkplain #mergeProperties merged local properties}, if {@linkplain #setLocation any}
	 * {@linkplain #setLocations have} {@linkplain #setProperties been}
	 * {@linkplain #setPropertiesArray specified}
	 * <li>any property sources set by calling {@link #setPropertySources}
	 * </ul>
	 * <p>If {@link #setPropertySources} is called, <strong>environment and local properties will be
	 * ignored</strong>. This method is designed to give the user fine-grained control over property
	 * sources, and once set, the configurer makes no assumptions about adding additional sources.
	 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    if (this.propertySources == null) {
        this.propertySources = new MutablePropertySources();
        if (this.environment != null) {
            this.propertySources.addLast(new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {

                @Override
                public String getProperty(String key) {
                    return this.source.getProperty(key);
                }
            });
        }
        try {
            PropertySource<?> localPropertySource = new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
            if (this.localOverride) {
                this.propertySources.addFirst(localPropertySource);
            } else {
                this.propertySources.addLast(localPropertySource);
            }
        } catch (IOException ex) {
            throw new BeanInitializationException("Could not load properties", ex);
        }
    }
    processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
    this.appliedPropertySources = this.propertySources;
}
Also used : BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) PropertySourcesPropertyResolver(org.springframework.core.env.PropertySourcesPropertyResolver) PropertiesPropertySource(org.springframework.core.env.PropertiesPropertySource) Environment(org.springframework.core.env.Environment) MutablePropertySources(org.springframework.core.env.MutablePropertySources) IOException(java.io.IOException)

Example 84 with Environment

use of org.springframework.core.env.Environment in project spring-boot by spring-projects.

the class EnvironmentEndpoint method getPropertySources.

private MutablePropertySources getPropertySources() {
    MutablePropertySources sources;
    Environment environment = getEnvironment();
    if (environment != null && environment instanceof ConfigurableEnvironment) {
        sources = ((ConfigurableEnvironment) environment).getPropertySources();
    } else {
        sources = new StandardEnvironment().getPropertySources();
    }
    return sources;
}
Also used : ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) StandardEnvironment(org.springframework.core.env.StandardEnvironment) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Environment(org.springframework.core.env.Environment) MutablePropertySources(org.springframework.core.env.MutablePropertySources) StandardEnvironment(org.springframework.core.env.StandardEnvironment)

Example 85 with Environment

use of org.springframework.core.env.Environment in project camel by apache.

the class CamelTestConfiguration method setApplicationContext.

/**
     * Build the URI of the CM Component based on Environmental properties
     */
@Override
public final void setApplicationContext(final ApplicationContext applicationContext) {
    super.setApplicationContext(applicationContext);
    final Environment env = applicationContext.getEnvironment();
    final String host = env.getRequiredProperty("cm.url");
    final String productTokenString = env.getRequiredProperty("cm.product-token");
    final String sender = env.getRequiredProperty("cm.default-sender");
    final StringBuffer cmUri = new StringBuffer("cm-sms:" + host).append("?productToken=").append(productTokenString);
    if (sender != null && !sender.isEmpty()) {
        cmUri.append("&defaultFrom=").append(sender);
    }
    // Defaults to false
    final Boolean testConnectionOnStartup = Boolean.parseBoolean(env.getProperty("cm.testConnectionOnStartup", "false"));
    if (testConnectionOnStartup) {
        cmUri.append("&testConnectionOnStartup=").append(testConnectionOnStartup.toString());
    }
    // Defaults to 8
    final Integer defaultMaxNumberOfParts = Integer.parseInt(env.getProperty("defaultMaxNumberOfParts", "8"));
    cmUri.append("&defaultMaxNumberOfParts=").append(defaultMaxNumberOfParts.toString());
    uri = cmUri.toString();
}
Also used : Environment(org.springframework.core.env.Environment)

Aggregations

Environment (org.springframework.core.env.Environment)161 Test (org.junit.jupiter.api.Test)68 StandardEnvironment (org.springframework.core.env.StandardEnvironment)30 EnvironmentVariableUtility (com.synopsys.integration.alert.environment.EnvironmentVariableUtility)26 MockEnvironment (org.springframework.mock.env.MockEnvironment)24 SpringApplication (org.springframework.boot.SpringApplication)21 EnvironmentProcessingResult (com.synopsys.integration.alert.environment.EnvironmentProcessingResult)19 EnvironmentVariableHandler (com.synopsys.integration.alert.environment.EnvironmentVariableHandler)19 EnvironmentVariableHandlerFactory (com.synopsys.integration.alert.environment.EnvironmentVariableHandlerFactory)19 HashMap (java.util.HashMap)13 ResourceLoader (org.springframework.core.io.ResourceLoader)13 Collectors (java.util.stream.Collectors)11 ConfigurableEnvironment (org.springframework.core.env.ConfigurableEnvironment)10 AlertIntegrationTest (com.synopsys.integration.alert.util.AlertIntegrationTest)9 MutablePropertySources (org.springframework.core.env.MutablePropertySources)8 AlertConstants (com.synopsys.integration.alert.api.common.model.AlertConstants)7 ChannelKeys (com.synopsys.integration.alert.descriptor.api.model.ChannelKeys)7 EnvironmentVariableMockingUtil (com.synopsys.integration.alert.test.common.EnvironmentVariableMockingUtil)7 Map (java.util.Map)7 Predicate (java.util.function.Predicate)7