Search in sources :

Example 1 with Environment

use of org.springframework.core.env.Environment 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 2 with Environment

use of org.springframework.core.env.Environment 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)

Example 3 with Environment

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

the class CamelCloudServiceCallConfigurationTest method doTest.

@Test
public void doTest() throws Exception {
    Environment env = ctx.getEnvironment();
    assertFalse(env.getProperty("camel.cloud.enabled", Boolean.class));
    assertFalse(env.getProperty("camel.cloud.service-discovery.enabled", Boolean.class));
    assertFalse(env.getProperty("camel.cloud.service-filter.enabled", Boolean.class));
    assertTrue(env.getProperty("camel.cloud.service-chooser.enabled", Boolean.class));
    assertFalse(env.getProperty("camel.cloud.load-balancer.enabled", Boolean.class));
    assertTrue(ctx.getBeansOfType(ServiceDiscovery.class).isEmpty());
    assertTrue(ctx.getBeansOfType(ServiceFilter.class).isEmpty());
    assertTrue(ctx.getBeansOfType(ServiceChooser.class).isEmpty());
    assertTrue(ctx.getBeansOfType(LoadBalancer.class).isEmpty());
}
Also used : Environment(org.springframework.core.env.Environment) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 4 with Environment

use of org.springframework.core.env.Environment in project nikita-noark5-core by HiOA-ABI.

the class N5CoreApp method main.

/**
 * Main method, used to run the application.
 *
 * @param args the command line arguments
 * @throws UnknownHostException if the local host name could not be resolved into an address
 */
public static void main(String[] args) throws UnknownHostException {
    ConfigurableApplicationContext context = SpringApplication.run(N5CoreApp.class, args);
    context.getBean(AfterApplicationStartup.class).afterApplicationStarts();
    Environment env = context.getEnvironment();
    String[] activeProfiles = env.getActiveProfiles();
    String profilesAsString = Arrays.toString(activeProfiles);
    logger.info("\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\t\thttp://localhost:{}\n\t" + "External: \t\thttp://{}:{}\n\t" + "contextPath: \thttp://{}:{}{} \n\t" + "Application is running with following profile(s): {} \n\t" + "\n----------------------------------------------------------", env.getProperty("server.application.name"), env.getProperty("server.port"), InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port"), InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port"), env.getProperty("server.servlet.context-path"), profilesAsString);
    String configServerStatus = env.getProperty("configserver.status");
    logger.info("\n----------------------------------------------------------\n\t" + "Config Server: \t{}\n----------------------------------------------------------", configServerStatus == null ? "Not found or not setup for this application" : configServerStatus);
    if (env.getProperty("spring.datasource.driver-class-name") != null && env.getProperty("spring.datasource.driver-class-name").equals("org.h2.Driver")) {
        logger.info("\n----------------------------------------------------------\n\t" + "Default profile in use. Using H2: In-memory database ({}). Access is available at." + "http://{}:{}{}{} \n\t. Make sure to use JDBC-string: jdbc:h2:mem:n5DemoDb" + "\n----------------------------------------------------------", env.getProperty("spring.jpa.database"), InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port"), env.getProperty("server.servlet.context-path"), env.getProperty("spring.h2.console.path"));
    }
}
Also used : ConfigurableApplicationContext(org.springframework.context.ConfigurableApplicationContext) AfterApplicationStartup(nikita.webapp.run.AfterApplicationStartup) Environment(org.springframework.core.env.Environment)

Example 5 with Environment

use of org.springframework.core.env.Environment in project jhipster-registry by jhipster.

the class JHipsterRegistryApp method main.

/**
 * Main method, used to run the application.
 *
 * @param args the command line arguments
 * @throws UnknownHostException if the local host name could not be resolved into an address
 */
public static void main(String[] args) throws UnknownHostException {
    SpringApplication app = new SpringApplication(JHipsterRegistryApp.class);
    DefaultProfileUtil.addDefaultProfile(app);
    Environment env = app.run(args).getEnvironment();
    String protocol = "http";
    if (env.getProperty("server.ssl.key-store") != null) {
        protocol = "https";
    }
    log.info("\n----------------------------------------------------------\n\t" + "Application '{}' is running! Access URLs:\n\t" + "Local: \t\t{}://localhost:{}\n\t" + "External: \t{}://{}:{}\n\t" + "Profile(s): \t{}\n----------------------------------------------------------", env.getProperty("spring.application.name"), protocol, env.getProperty("server.port"), protocol, InetAddress.getLocalHost().getHostAddress(), env.getProperty("server.port"), env.getActiveProfiles());
    String secretKey = env.getProperty("jhipster.security.authentication.jwt.secret");
    if (secretKey == null) {
        log.error("\n----------------------------------------------------------\n" + "Your JWT secret key is not set up, you will not be able to log into the JHipster.\n" + "Please read the documentation at http://www.jhipster.tech/jhipster-registry/\n" + "----------------------------------------------------------");
    } else if (secretKey.equals("this-secret-should-not-be-used-read-the-comment")) {
        log.error("\n----------------------------------------------------------\n" + "Your JWT secret key is not configured using Spring Cloud Config, you will not be able to \n" + "use the JHipster Registry dashboards to monitor external applications. \n" + "Please read the documentation at http://www.jhipster.tech/jhipster-registry/\n" + "----------------------------------------------------------");
    }
}
Also used : SpringApplication(org.springframework.boot.SpringApplication) Environment(org.springframework.core.env.Environment)

Aggregations

Environment (org.springframework.core.env.Environment)159 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