Search in sources :

Example 16 with ConfigurableEnvironment

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

the class TestPropertySourceUtilsTests method addPropertiesFilesToEnvironmentWithSinglePropertyFromVirtualFile.

@Test
public void addPropertiesFilesToEnvironmentWithSinglePropertyFromVirtualFile() {
    ConfigurableEnvironment environment = new MockEnvironment();
    MutablePropertySources propertySources = environment.getPropertySources();
    propertySources.remove(MockPropertySource.MOCK_PROPERTIES_PROPERTY_SOURCE_NAME);
    assertEquals(0, propertySources.size());
    String pair = "key = value";
    ByteArrayResource resource = new ByteArrayResource(pair.getBytes(), "from inlined property: " + pair);
    ResourceLoader resourceLoader = mock(ResourceLoader.class);
    when(resourceLoader.getResource(anyString())).thenReturn(resource);
    addPropertiesFilesToEnvironment(environment, resourceLoader, FOO_LOCATIONS);
    assertEquals(1, propertySources.size());
    assertEquals("value", environment.getProperty("key"));
}
Also used : ResourceLoader(org.springframework.core.io.ResourceLoader) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) MockEnvironment(org.springframework.mock.env.MockEnvironment) MutablePropertySources(org.springframework.core.env.MutablePropertySources) ByteArrayResource(org.springframework.core.io.ByteArrayResource) Test(org.junit.Test)

Example 17 with ConfigurableEnvironment

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

the class AutoConfigurationImportSelector method getExcludeAutoConfigurationsProperty.

private List<String> getExcludeAutoConfigurationsProperty() {
    if (getEnvironment() instanceof ConfigurableEnvironment) {
        RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(this.environment, "spring.autoconfigure.");
        Map<String, Object> properties = resolver.getSubProperties("exclude");
        if (properties.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> excludes = new ArrayList<>();
        for (Map.Entry<String, Object> entry : properties.entrySet()) {
            String name = entry.getKey();
            Object value = entry.getValue();
            if (name.isEmpty() || name.startsWith("[") && value != null) {
                excludes.addAll(new HashSet<>(Arrays.asList(StringUtils.tokenizeToStringArray(String.valueOf(value), ","))));
            }
        }
        return excludes;
    }
    RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(getEnvironment(), "spring.autoconfigure.");
    String[] exclude = resolver.getProperty("exclude", String[].class);
    return (Arrays.asList(exclude == null ? new String[0] : exclude));
}
Also used : ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) RelaxedPropertyResolver(org.springframework.boot.bind.RelaxedPropertyResolver) ArrayList(java.util.ArrayList) Map(java.util.Map)

Example 18 with ConfigurableEnvironment

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

the class OnBootstrapHostsCondition method getMatchOutcome.

@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    Environment environment = context.getEnvironment();
    PropertyResolver resolver = new PropertyResolver(((ConfigurableEnvironment) environment).getPropertySources(), "spring.couchbase");
    Map.Entry<String, Object> entry = resolver.resolveProperty("bootstrap-hosts");
    if (entry != null) {
        return ConditionOutcome.match(ConditionMessage.forCondition(OnBootstrapHostsCondition.class.getName()).found("property").items("spring.couchbase.bootstrap-hosts"));
    }
    return ConditionOutcome.noMatch(ConditionMessage.forCondition(OnBootstrapHostsCondition.class.getName()).didNotFind("property").items("spring.couchbase.bootstrap-hosts"));
}
Also used : ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Environment(org.springframework.core.env.Environment) HashMap(java.util.HashMap) AbstractMap(java.util.AbstractMap) Map(java.util.Map)

Example 19 with ConfigurableEnvironment

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

the class DispatcherServletTests method environmentOperations.

@Test
public void environmentOperations() {
    DispatcherServlet servlet = new DispatcherServlet();
    ConfigurableEnvironment defaultEnv = servlet.getEnvironment();
    assertThat(defaultEnv, notNullValue());
    ConfigurableEnvironment env1 = new StandardServletEnvironment();
    // should succeed
    servlet.setEnvironment(env1);
    assertThat(servlet.getEnvironment(), sameInstance(env1));
    try {
        servlet.setEnvironment(new DummyEnvironment());
        fail("expected IllegalArgumentException for non-configurable Environment");
    } catch (IllegalArgumentException ex) {
    }
    class CustomServletEnvironment extends StandardServletEnvironment {
    }
    @SuppressWarnings("serial") DispatcherServlet custom = new DispatcherServlet() {

        @Override
        protected ConfigurableWebEnvironment createEnvironment() {
            return new CustomServletEnvironment();
        }
    };
    assertThat(custom.getEnvironment(), instanceOf(CustomServletEnvironment.class));
}
Also used : ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) DummyEnvironment(org.springframework.core.env.DummyEnvironment) StandardServletEnvironment(org.springframework.web.context.support.StandardServletEnvironment) Test(org.junit.Test)

Example 20 with ConfigurableEnvironment

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

the class CamelAutoConfiguration method camelContext.

/**
     * Spring-aware Camel context for the application. Auto-detects and loads all routes available in the Spring context.
     */
@Bean
@ConditionalOnMissingBean(CamelContext.class)
CamelContext camelContext(ApplicationContext applicationContext, CamelConfigurationProperties config) {
    if (ObjectHelper.isNotEmpty(config.getFileConfigurations())) {
        Environment env = applicationContext.getEnvironment();
        if (env instanceof ConfigurableEnvironment) {
            MutablePropertySources sources = ((ConfigurableEnvironment) env).getPropertySources();
            if (sources != null) {
                if (!sources.contains("camel-file-configuration")) {
                    sources.addFirst(new FilePropertySource("camel-file-configuration", applicationContext, config.getFileConfigurations()));
                }
            }
        }
    }
    CamelContext camelContext = new SpringCamelContext(applicationContext);
    SpringCamelContext.setNoStart(true);
    if (!config.isJmxEnabled()) {
        camelContext.disableJMX();
    }
    if (config.getName() != null) {
        ((SpringCamelContext) camelContext).setName(config.getName());
    }
    if (config.getShutdownTimeout() > 0) {
        camelContext.getShutdownStrategy().setTimeout(config.getShutdownTimeout());
    }
    camelContext.getShutdownStrategy().setSuppressLoggingOnTimeout(config.isShutdownSuppressLoggingOnTimeout());
    camelContext.getShutdownStrategy().setShutdownNowOnTimeout(config.isShutdownNowOnTimeout());
    camelContext.getShutdownStrategy().setShutdownRoutesInReverseOrder(config.isShutdownRoutesInReverseOrder());
    camelContext.getShutdownStrategy().setLogInflightExchangesOnTimeout(config.isShutdownLogInflightExchangesOnTimeout());
    if (config.getLogDebugMaxChars() > 0) {
        camelContext.getGlobalOptions().put(Exchange.LOG_DEBUG_BODY_MAX_CHARS, "" + config.getLogDebugMaxChars());
    }
    // stream caching
    camelContext.setStreamCaching(config.isStreamCachingEnabled());
    camelContext.getStreamCachingStrategy().setAnySpoolRules(config.isStreamCachingAnySpoolRules());
    camelContext.getStreamCachingStrategy().setBufferSize(config.getStreamCachingBufferSize());
    camelContext.getStreamCachingStrategy().setRemoveSpoolDirectoryWhenStopping(config.isStreamCachingRemoveSpoolDirectoryWhenStopping());
    camelContext.getStreamCachingStrategy().setSpoolChiper(config.getStreamCachingSpoolChiper());
    if (config.getStreamCachingSpoolDirectory() != null) {
        camelContext.getStreamCachingStrategy().setSpoolDirectory(config.getStreamCachingSpoolDirectory());
    }
    if (config.getStreamCachingSpoolThreshold() != 0) {
        camelContext.getStreamCachingStrategy().setSpoolThreshold(config.getStreamCachingSpoolThreshold());
    }
    if (config.getStreamCachingSpoolUsedHeapMemoryLimit() != null) {
        StreamCachingStrategy.SpoolUsedHeapMemoryLimit limit;
        if ("Committed".equalsIgnoreCase(config.getStreamCachingSpoolUsedHeapMemoryLimit())) {
            limit = StreamCachingStrategy.SpoolUsedHeapMemoryLimit.Committed;
        } else if ("Max".equalsIgnoreCase(config.getStreamCachingSpoolUsedHeapMemoryLimit())) {
            limit = StreamCachingStrategy.SpoolUsedHeapMemoryLimit.Max;
        } else {
            throw new IllegalArgumentException("Invalid option " + config.getStreamCachingSpoolUsedHeapMemoryLimit() + " must either be Committed or Max");
        }
        camelContext.getStreamCachingStrategy().setSpoolUsedHeapMemoryLimit(limit);
    }
    if (config.getStreamCachingSpoolUsedHeapMemoryThreshold() != 0) {
        camelContext.getStreamCachingStrategy().setSpoolUsedHeapMemoryThreshold(config.getStreamCachingSpoolUsedHeapMemoryThreshold());
    }
    camelContext.setMessageHistory(config.isMessageHistory());
    camelContext.setLogExhaustedMessageBody(config.isLogExhaustedMessageBody());
    camelContext.setHandleFault(config.isHandleFault());
    camelContext.setAutoStartup(config.isAutoStartup());
    camelContext.setAllowUseOriginalMessage(config.isAllowUseOriginalMessage());
    if (camelContext.getManagementStrategy().getManagementAgent() != null) {
        camelContext.getManagementStrategy().getManagementAgent().setEndpointRuntimeStatisticsEnabled(config.isEndpointRuntimeStatisticsEnabled());
        camelContext.getManagementStrategy().getManagementAgent().setStatisticsLevel(config.getJmxManagementStatisticsLevel());
        camelContext.getManagementStrategy().getManagementAgent().setManagementNamePattern(config.getJmxManagementNamePattern());
        camelContext.getManagementStrategy().getManagementAgent().setCreateConnector(config.isJmxCreateConnector());
    }
    camelContext.setPackageScanClassResolver(new FatJarPackageScanClassResolver());
    // tracing
    camelContext.setTracing(config.isTracing());
    if (camelContext.getDefaultTracer() instanceof Tracer) {
        Tracer tracer = (Tracer) camelContext.getDefaultTracer();
        if (tracer.getDefaultTraceFormatter() != null) {
            DefaultTraceFormatter formatter = tracer.getDefaultTraceFormatter();
            if (config.getTracerFormatterBreadCrumbLength() != null) {
                formatter.setBreadCrumbLength(config.getTracerFormatterBreadCrumbLength());
            }
            if (config.getTracerFormatterMaxChars() != null) {
                formatter.setMaxChars(config.getTracerFormatterMaxChars());
            }
            if (config.getTracerFormatterNodeLength() != null) {
                formatter.setNodeLength(config.getTracerFormatterNodeLength());
            }
            formatter.setShowBody(config.isTraceFormatterShowBody());
            formatter.setShowBodyType(config.isTracerFormatterShowBodyType());
            formatter.setShowBreadCrumb(config.isTraceFormatterShowBreadCrumb());
            formatter.setShowException(config.isTraceFormatterShowException());
            formatter.setShowExchangeId(config.isTraceFormatterShowExchangeId());
            formatter.setShowExchangePattern(config.isTraceFormatterShowExchangePattern());
            formatter.setShowHeaders(config.isTraceFormatterShowHeaders());
            formatter.setShowNode(config.isTraceFormatterShowNode());
            formatter.setShowProperties(config.isTraceFormatterShowProperties());
            formatter.setShowRouteId(config.isTraceFormatterShowRouteId());
            formatter.setShowShortExchangeId(config.isTraceFormatterShowShortExchangeId());
        }
    }
    if (config.getXmlRoutesReloadDirectory() != null) {
        ReloadStrategy reload = new FileWatcherReloadStrategy(config.getXmlRoutesReloadDirectory());
        camelContext.setReloadStrategy(reload);
    }
    // additional advanced configuration which is not configured using CamelConfigurationProperties
    afterPropertiesSet(applicationContext, camelContext);
    return camelContext;
}
Also used : SpringCamelContext(org.apache.camel.spring.SpringCamelContext) CamelContext(org.apache.camel.CamelContext) DefaultTraceFormatter(org.apache.camel.processor.interceptor.DefaultTraceFormatter) FileWatcherReloadStrategy(org.apache.camel.impl.FileWatcherReloadStrategy) Tracer(org.apache.camel.processor.interceptor.Tracer) BacklogTracer(org.apache.camel.processor.interceptor.BacklogTracer) SpringCamelContext(org.apache.camel.spring.SpringCamelContext) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Environment(org.springframework.core.env.Environment) MutablePropertySources(org.springframework.core.env.MutablePropertySources) StreamCachingStrategy(org.apache.camel.spi.StreamCachingStrategy) ReloadStrategy(org.apache.camel.spi.ReloadStrategy) FileWatcherReloadStrategy(org.apache.camel.impl.FileWatcherReloadStrategy) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Aggregations

ConfigurableEnvironment (org.springframework.core.env.ConfigurableEnvironment)54 Test (org.junit.Test)27 StandardEnvironment (org.springframework.core.env.StandardEnvironment)18 MutablePropertySources (org.springframework.core.env.MutablePropertySources)10 SpringApplication (org.springframework.boot.SpringApplication)7 ConfigurableApplicationContext (org.springframework.context.ConfigurableApplicationContext)6 MockEnvironment (org.springframework.mock.env.MockEnvironment)6 CompositePropertySource (org.springframework.core.env.CompositePropertySource)4 MapPropertySource (org.springframework.core.env.MapPropertySource)4 Environment (org.springframework.core.env.Environment)3 ProfileAnnotatedComponent (example.profilescan.ProfileAnnotatedComponent)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 PrintStream (java.io.PrintStream)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 AnnotatedGenericBeanDefinition (org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition)2 BeanDefinition (org.springframework.beans.factory.config.BeanDefinition)2 DefaultListableBeanFactory (org.springframework.beans.factory.support.DefaultListableBeanFactory)2 CommandLinePropertySource (org.springframework.core.env.CommandLinePropertySource)2 PropertySource (org.springframework.core.env.PropertySource)2