List of usage examples for org.springframework.core.env ConfigurableEnvironment getProperty
@Nullable String getProperty(String key);
From source file:com.devnexus.ting.web.config.DefaultApplicationContextInitializer.java
@Override public void initialize(ConfigurableApplicationContext applicationContext) { final CloudEnvironment env = new CloudEnvironment(); if (env.getInstanceInfo() != null) { LOGGER.info("cloud API: " + env.getCloudApiUri()); applicationContext.getEnvironment().setActiveProfiles("cloud", SpringContextMode.DemoContextConfiguration.getCode()); } else {/* w w w. j av a 2 s .c o m*/ final String profile = System.getProperty("ting-spring-profile"); if (profile == null) { LOGGER.info("System property 'ting-spring-profile' not set. Setting active profile to '{}'.", SpringContextMode.DemoContextConfiguration.getCode()); applicationContext.getEnvironment() .setActiveProfiles(SpringContextMode.DemoContextConfiguration.getCode()); } else { applicationContext.getEnvironment().setActiveProfiles(profile); } } final ConfigurableEnvironment environment = applicationContext.getEnvironment(); if (environment.acceptsProfiles(SpringProfile.STANDALONE)) { final String tingHome = environment.getProperty(Apphome.APP_HOME_DIRECTORY); final ResourcePropertySource propertySource; final String productionPropertySourceLocation = "file:" + tingHome + File.separator + SystemInformationUtils.TING_CONFIG_FILENAME; try { propertySource = new ResourcePropertySource(productionPropertySourceLocation); } catch (IOException e) { throw new IllegalStateException( "Unable to get ResourcePropertySource '" + productionPropertySourceLocation + "'", e); } environment.getPropertySources().addFirst(propertySource); LOGGER.info("Properties for standalone mode loaded [" + productionPropertySourceLocation + "]"); } else { final String demoPropertySourceLocation = "classpath:ting-demo.properties"; final ResourcePropertySource propertySource; try { propertySource = new ResourcePropertySource(demoPropertySourceLocation); } catch (IOException e) { throw new IllegalStateException( "Unable to get ResourcePropertySource '" + demoPropertySourceLocation + "'", e); } environment.getPropertySources().addFirst(propertySource); LOGGER.info("Properties for demo mode loaded [" + demoPropertySourceLocation + "]"); } final boolean mailEnabled = environment.getProperty("mail.enabled", Boolean.class, Boolean.FALSE); final boolean twitterEnabled = environment.getProperty("twitter.enabled", Boolean.class, Boolean.FALSE); final boolean websocketEnabled = environment.getProperty("websocket.enabled", Boolean.class, Boolean.FALSE); if (mailEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.MAIL_ENABLED); } if (twitterEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.TWITTER_ENABLED); } if (websocketEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.WEBSOCKET_ENABLED); } }
From source file:com.pavikumbhar.javaheart.springconfiguration.ContextInitializer.java
@Override public void initialize(ConfigurableApplicationContext applicationContext) { ConfigurableEnvironment environment = applicationContext.getEnvironment(); System.out.println("com.pavikumbhar.javaheart.ContextInitializer.initialize()"); try {/*from w w w.j a va 2s . c om*/ environment.getPropertySources().addFirst(new ResourcePropertySource("classpath:env.properties")); String profile = environment.getProperty("spring.profiles.active"); environment.setActiveProfiles(profile); System.err.println(" spring.profiles.active profile :" + profile); System.err.println("env.properties loaded :" + ContextInitializer.class.getName()); } catch (IOException e) { // it's ok if the file is not there. we will just log that info. System.out.println( "didn't find env.properties in classpath so not loading it in the AppContextInitialized"); } }
From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializer.java
private void applyLog4jConfiguration(ConfigurableEnvironment environment, ServletContext servletContext) { String log4jConfigLocation = "classpath:log4j.properties"; if (environment.containsProperty("logging.file")) { String location = environment.getProperty("logging.file"); servletContext.log("Setting LOG_FILE: " + location); System.setProperty("LOG_FILE", location); }// w ww . ja v a2 s .com else if (environment.containsProperty("logging.path")) { String location = environment.getProperty("logging.path"); servletContext.log("Setting LOG_PATH: " + location); System.setProperty("LOG_PATH", location); } else if (environment.containsProperty("logging.config")) { log4jConfigLocation = environment.getProperty("logging.config"); } try { servletContext.log("Loading log4j config from location: " + log4jConfigLocation); Log4jConfigurer.initLogging(log4jConfigLocation); } catch (FileNotFoundException e) { servletContext.log("Error loading log4j config from location: " + log4jConfigLocation, e); } MDC.put("context", servletContext.getContextPath()); }
From source file:com.devnexus.ting.DefaultApplicationContextInitializer.java
@Override public void initialize(ConfigurableApplicationContext applicationContext) { final CloudEnvironment env = new CloudEnvironment(); if (env.getInstanceInfo() != null) { LOGGER.info("Running in the cloud - API: " + env.getCloudApiUri()); applicationContext.getEnvironment().setActiveProfiles(SpringProfile.CLOUD); } else {/*from w ww. ja va 2s . co m*/ final Apphome apphome = SystemInformationUtils.retrieveBasicSystemInformation(); SpringContextMode springContextMode; LOGGER.info("DevNexus Apphome: " + apphome); if (SystemInformationUtils.existsConfigFile(apphome.getAppHomePath())) { springContextMode = SpringContextMode.ProductionContextConfiguration; } else { springContextMode = SpringContextMode.DemoContextConfiguration; } applicationContext.getEnvironment().setActiveProfiles(springContextMode.getCode()); } final ConfigurableEnvironment environment = applicationContext.getEnvironment(); if (environment.acceptsProfiles(SpringProfile.STANDALONE)) { final String tingHome = environment.getProperty(Apphome.APP_HOME_DIRECTORY); final PropertySource<?> propertySource; final YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader(); final String productionPropertySourceLocation; final Apphome apphome = SystemInformationUtils.retrieveBasicSystemInformation(); if (apphome.getAppHomeSource() == AppHomeSource.USER_DIRECTORY) { productionPropertySourceLocation = "file:" + apphome.getAppHomePath() + File.separator + SystemInformationUtils.TING_CONFIG_FILENAME; } else { productionPropertySourceLocation = "file:" + tingHome + File.separator + SystemInformationUtils.TING_CONFIG_FILENAME; } try { propertySource = yamlPropertySourceLoader.load("devnexus-standalone", new DefaultResourceLoader().getResource(productionPropertySourceLocation), null); } catch (IOException e) { throw new IllegalStateException( "Unable to get ResourcePropertySource '" + productionPropertySourceLocation + "'", e); } environment.getPropertySources().addFirst(propertySource); LOGGER.info("Properties for standalone mode loaded [" + productionPropertySourceLocation + "]."); } else { LOGGER.info("Using Properties for demo mode."); } final String emailProviderAsString = environment.getProperty("devnexus.mail.emailProvider"); final EmailProvider emailProvider = EmailProvider.valueOf(emailProviderAsString.trim().toUpperCase()); final boolean twitterEnabled = environment.getProperty("devnexus.twitter.enabled", Boolean.class, Boolean.FALSE); final boolean websocketEnabled = environment.getProperty("devnexus.websocket.enabled", Boolean.class, Boolean.FALSE); final boolean payPalEnabled = environment.containsProperty("PAYPAL_MODE"); LOGGER.info("Uses Settings:" + "\nEmail Provider: " + emailProvider + "\nTwitter Enabled: " + twitterEnabled + "\nPayPal Enabled: " + payPalEnabled + "\nWebsocket Enabled: " + websocketEnabled); if (EmailProvider.SENDGRID.equals(emailProvider)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.SENDGRID_ENABLED); } else if (EmailProvider.SMTP.equals(emailProvider)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.SMTP_ENABLED); } else if (EmailProvider.AMAZON_SES.equals(emailProvider)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.AMAZON_SES_ENABLED); } else if (EmailProvider.NONE.equals(emailProvider)) { } else { throw new IllegalArgumentException("Unknown EmailProvider: " + emailProvider); } if (!EmailProvider.NONE.equals(emailProvider)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.MAIL_ENABLED); } if (twitterEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.TWITTER_ENABLED); } if (websocketEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.WEBSOCKET_ENABLED); } if (payPalEnabled) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_ENABLED); switch (environment.getProperty("PAYPAL_MODE")) { case "live": applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_LIVE); break; default: applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_SANDBOX); break; } } if (environment.getProperty("DEVELOPMENT_MODE", Boolean.class, Boolean.FALSE)) { applicationContext.getEnvironment().addActiveProfile(SpringProfile.DEVELOPMENT_ENABLED); } }
From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.security.preauth.WebAnnoApplicationContextInitializer.java
@Override public void initialize(ConfigurableApplicationContext aApplicationContext) { WebAnnoLoggingFilter.setLoggingUsername("SYSTEM"); log.info(" _ __ __ ___ "); log.info(" | | /| / /__ / / / _ | ___ ___ ___ "); log.info(" | |/ |/ / -_) _ \\/ __ |/ _ \\/ _ \\/ _ \\"); log.info(" |__/|__/\\__/_.__/_/ |_/_//_/_//_/\\___/"); log.info(SettingsUtil.getVersionString()); ConfigurableEnvironment aEnvironment = aApplicationContext.getEnvironment(); File settings = SettingsUtil.getSettingsFile(); // If settings were found, add them to the environment if (settings != null) { log.info("Settings: " + settings); try {//from w w w . j a v a 2 s.c o m aEnvironment.getPropertySources() .addFirst(new ResourcePropertySource(new FileSystemResource(settings))); } catch (IOException e) { throw new IllegalStateException(e); } } // Activate bean profile depending on authentication mode if (AUTH_MODE_PREAUTH.equals(aEnvironment.getProperty(PROP_AUTH_MODE))) { aEnvironment.setActiveProfiles(PROFILE_PREAUTH); log.info("Authentication: pre-auth"); } else { aEnvironment.setActiveProfiles(PROFILE_DATABASE); log.info("Authentication: database"); } }
From source file:io.bitsquare.app.BitsquareEnvironmentTests.java
@Test public void testPropertySourcePrecedence() { PropertySource commandlineProps = new MockPropertySource(BITSQUARE_COMMANDLINE_PROPERTY_SOURCE_NAME) .withProperty("key.x", "x.commandline"); PropertySource filesystemProps = new MockPropertySource(BITSQUARE_FILESYSTEM_PROPERTY_SOURCE_NAME) .withProperty("key.x", "x.env").withProperty("key.y", "y.env"); ConfigurableEnvironment env = new BitsquareEnvironment(commandlineProps) { @Override//from w ww . j a v a 2 s . co m PropertySource<?> filesystemProperties() { return filesystemProps; } }; MutablePropertySources propertySources = env.getPropertySources(); assertThat(propertySources.precedenceOf(named(BITSQUARE_COMMANDLINE_PROPERTY_SOURCE_NAME)), equalTo(0)); assertThat(propertySources.precedenceOf(named(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(1)); assertThat(propertySources.precedenceOf(named(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(2)); assertThat(propertySources.precedenceOf(named(BITSQUARE_FILESYSTEM_PROPERTY_SOURCE_NAME)), equalTo(3)); assertThat(propertySources.precedenceOf(named(BITSQUARE_CLASSPATH_PROPERTY_SOURCE_NAME)), equalTo(4)); assertThat(propertySources.precedenceOf(named(BITSQUARE_DEFAULT_PROPERTY_SOURCE_NAME)), equalTo(5)); assertThat(propertySources.size(), equalTo(6)); assertThat(env.getProperty("key.x"), equalTo("x.commandline")); // commandline value wins due to precedence assertThat(env.getProperty("key.y"), equalTo("y.env")); // env value wins because it's the only one available }
From source file:org.apache.servicecomb.config.ConfigurationSpringInitializer.java
/** * Get property names from {@link EnumerablePropertySource}, and get property value from {@link ConfigurableEnvironment#getProperty(String)} *///from w w w . j a v a 2s .c om private void getProperties(ConfigurableEnvironment environment, PropertySource<?> propertySource, Map<String, Object> configFromSpringBoot) { if (propertySource instanceof CompositePropertySource) { // recursively get EnumerablePropertySource CompositePropertySource compositePropertySource = (CompositePropertySource) propertySource; compositePropertySource.getPropertySources() .forEach(ps -> getProperties(environment, ps, configFromSpringBoot)); return; } if (propertySource instanceof EnumerablePropertySource) { EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) propertySource; for (String propertyName : enumerablePropertySource.getPropertyNames()) { configFromSpringBoot.put(propertyName, environment.getProperty(propertyName)); } return; } LOGGER.debug("a none EnumerablePropertySource is ignored, propertySourceName = [{}]", propertySource.getName()); }
From source file:org.apache.servicecomb.config.TestConfigurationSpringInitializer.java
@Test public void testSetEnvironmentOnEnvironmentName() { // get environment name from spring.config.name ConfigurableEnvironment environment0 = Mockito.mock(ConfigurableEnvironment.class); MutablePropertySources propertySources0 = new MutablePropertySources(); Mockito.when(environment0.getPropertySources()).thenReturn(propertySources0); Map<String, Object> map0 = new HashMap<>(1); map0.put("spring.config.name", "application"); propertySources0.addFirst(new MapPropertySource("mapPropertySource0", map0)); Mockito.when(environment0.getProperty("spring.config.name")).thenReturn("application"); // get environment name from spring.application.name ConfigurableEnvironment environment1 = Mockito.mock(ConfigurableEnvironment.class); MutablePropertySources propertySources1 = new MutablePropertySources(); Mockito.when(environment1.getPropertySources()).thenReturn(propertySources1); Map<String, Object> map1 = new HashMap<>(1); map1.put("spring.application.name", "bootstrap"); propertySources1.addFirst(new MapPropertySource("mapPropertySource1", map1)); Mockito.when(environment1.getProperty("spring.application.name")).thenReturn("bootstrap"); // get environment name from className+hashcode ConfigurableEnvironment environment2 = Mockito.mock(ConfigurableEnvironment.class); MutablePropertySources propertySources2 = new MutablePropertySources(); Mockito.when(environment2.getPropertySources()).thenReturn(propertySources2); Map<String, Object> map2 = new HashMap<>(1); map2.put("key2", "value2"); propertySources2.addFirst(new MapPropertySource("mapPropertySource2", map2)); Mockito.when(environment2.getProperty("key2")).thenReturn("value2"); ConfigurationSpringInitializer configurationSpringInitializer = new ConfigurationSpringInitializer(); configurationSpringInitializer.setEnvironment(environment0); configurationSpringInitializer.setEnvironment(environment1); configurationSpringInitializer.setEnvironment(environment2); Map<String, Map<String, Object>> extraConfig = getExtraConfigMapFromConfigUtil(); assertEquals(3, extraConfig.size()); Map<String, Object> extraProperties = extraConfig .get(ConfigurationSpringInitializer.EXTRA_CONFIG_SOURCE_PREFIX + "application"); assertEquals(1, extraProperties.size()); assertEquals("application", extraProperties.get("spring.config.name")); extraProperties = extraConfig.get(ConfigurationSpringInitializer.EXTRA_CONFIG_SOURCE_PREFIX + "bootstrap"); assertEquals(1, extraProperties.size()); assertEquals("bootstrap", extraProperties.get("spring.application.name")); extraProperties = extraConfig.get(ConfigurationSpringInitializer.EXTRA_CONFIG_SOURCE_PREFIX + environment2.getClass().getName() + "@" + environment2.hashCode()); assertEquals(1, extraProperties.size()); assertEquals("value2", extraProperties.get("key2")); }
From source file:org.dspace.app.rest.utils.DSpaceKernelInitializer.java
/** * Find DSpace's "home" directory (from current environment) * Initially look for JNDI Resource called "java:/comp/env/dspace.dir". * If not found, use value provided in "dspace.dir" in Spring Environment *//*from w w w .j a v a2s.c o m*/ private String getDSpaceHome(ConfigurableEnvironment environment) { // Load the "dspace.dir" property from Spring Boot's Configuration (application.properties) // This gives us the location of our DSpace configurations, necessary to start the kernel String providedHome = environment.getProperty(DSpaceConfigurationService.DSPACE_HOME); String dspaceHome = null; try { // Allow ability to override home directory via JNDI Context ctx = new InitialContext(); dspaceHome = (String) ctx.lookup("java:/comp/env/" + DSpaceConfigurationService.DSPACE_HOME); } catch (Exception e) { // do nothing } // Otherwise, verify the 'providedHome' value is non-empty, exists and includes DSpace configs if (dspaceHome == null) { if (StringUtils.isNotBlank(providedHome) && !providedHome.equals("${" + DSpaceConfigurationService.DSPACE_HOME + "}")) { File test = new File(providedHome); if (test.exists() && new File(test, DSpaceConfigurationService.DSPACE_CONFIG_PATH).exists()) { dspaceHome = providedHome; } } } return dspaceHome; }
From source file:org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration.java
/** * Add an alias for 'local.management.port' that actually resolves using * 'local.server.port'./*from www.j a v a 2s . c om*/ * @param environment the environment */ private void addLocalManagementPortPropertyAlias(final ConfigurableEnvironment environment) { environment.getPropertySources().addLast(new PropertySource<Object>("Management Server") { @Override public Object getProperty(String name) { if ("local.management.port".equals(name)) { return environment.getProperty("local.server.port"); } return null; } }); }