org.springframework.core.env.ConfigurableEnvironment Java Examples

The following examples show how to use org.springframework.core.env.ConfigurableEnvironment. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OverrideDubboConfigApplicationListener.java    From dubbo-spring-boot-project with Apache License 2.0 21 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {

    /**
     * Gets Logger After LoggingSystem configuration ready
     * @see LoggingApplicationListener
     */
    final Logger logger = LoggerFactory.getLogger(getClass());

    ConfigurableEnvironment environment = event.getEnvironment();

    boolean override = environment.getProperty(OVERRIDE_CONFIG_FULL_PROPERTY_NAME, boolean.class,
            DEFAULT_OVERRIDE_CONFIG_PROPERTY_VALUE);

    if (override) {

        SortedMap<String, Object> dubboProperties = filterDubboProperties(environment);

        ConfigUtils.getProperties().putAll(dubboProperties);

        if (logger.isInfoEnabled()) {
            logger.info("Dubbo Config was overridden by externalized configuration {}", dubboProperties);
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("Disable override Dubbo Config caused by property {} = {}", OVERRIDE_CONFIG_FULL_PROPERTY_NAME, override);
        }
    }

}
 
Example #2
Source File: SpringBootUrlReplacer.java    From Cleanstone with MIT License 7 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    ConfigurableEnvironment environment = applicationContext.getEnvironment();

    String springBootAdminServerUrl = environment.getProperty("web.client.url");
    if (environment.getProperty("web.admin.enabled", Boolean.class, false)) {
        springBootAdminServerUrl = "http://" + environment.getProperty("web.server.address") + ":" + environment.getProperty("web.server.port");
    }
    properties.put("spring.boot.admin.client.url", springBootAdminServerUrl);

    properties.put("spring.boot.admin.ui.public-url", environment.getProperty("web.admin.url"));
    properties.put("server.port", environment.getProperty("web.server.port"));
    properties.put("server.address", environment.getProperty("web.server.address"));

    environment.getPropertySources().addFirst(new PropertySource<>("spring-boot-admin-property-source") {
        @Override
        public Object getProperty(@NonNull String name) {
            if (properties.containsKey(name)) {
                return properties.get(name);
            }
            return null;
        }
    });
}
 
Example #3
Source File: MyEnvironmentPostProcessor.java    From springCloud with MIT License 7 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment,SpringApplication application) {
    //自定义配置文件
    String[] profiles = {
            "eureka.properties",
            "datasource.properties",
            "config.properties",
            "tx-lcn.properties",
            "feign.properties"
    };

    //循环添加
    for (String profile : profiles) {
        //从classpath路径下面查找文件
        Resource resource = new ClassPathResource(profile);
        //加载成PropertySource对象,并添加到Environment环境中
        environment.getPropertySources().addLast(loadProfiles(resource));
    }
}
 
Example #4
Source File: NestedBeansElementTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void getBean_withActiveProfile() {
	ConfigurableEnvironment env = new StandardEnvironment();
	env.setActiveProfiles("dev");

	DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
	XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
	reader.setEnvironment(env);
	reader.loadBeanDefinitions(XML);

	bf.getBean("devOnlyBean"); // should not throw NSBDE

	Object foo = bf.getBean("foo");
	assertThat(foo, instanceOf(Integer.class));

	bf.getBean("devOnlyBean");
}
 
Example #5
Source File: ClientSecurityAutoConfigurationUnitTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Test
public void clientSecurityIsDisabledWhenEnablePropertyIsTrueAndCloudFoundryIsNotActive() {

	AutoConfiguredCloudSecurityEnvironmentPostProcessor environmentPostProcessor =
		spy(new AutoConfiguredCloudSecurityEnvironmentPostProcessor());

	doNothing().when(environmentPostProcessor).configureSecurityContext(any(ConfigurableEnvironment.class));

	ConfigurableEnvironment mockEnvironment = mock(ConfigurableEnvironment.class);

	when(mockEnvironment.containsProperty(eq("VCAP_APPLICATION"))).thenReturn(false);
	when(mockEnvironment.containsProperty(eq("VCAP_SERVICES"))).thenReturn(false);

	when(mockEnvironment.getProperty(eq(ClientSecurityAutoConfiguration.CLOUD_SECURITY_ENVIRONMENT_POST_PROCESSOR_ENABLED_PROPERTY),
		eq(Boolean.class), eq(true))).thenReturn(true);

	environmentPostProcessor.postProcessEnvironment(mockEnvironment, null);

	verify(mockEnvironment, times(1))
		.getProperty(eq(ClientSecurityAutoConfiguration.CLOUD_SECURITY_ENVIRONMENT_POST_PROCESSOR_ENABLED_PROPERTY),
			eq(Boolean.class), eq(true));

	verify(mockEnvironment, times(1)).containsProperty(eq("VCAP_APPLICATION"));
	verify(mockEnvironment, times(1)).containsProperty(eq("VCAP_SERVICES"));
	verify(environmentPostProcessor, never()).configureSecurityContext(eq(mockEnvironment));
}
 
Example #6
Source File: GrayClientImportSelector.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
@Override
public String[] selectImports(AnnotationMetadata metadata) {
    String[] imports = super.selectImports(metadata);

    Environment env = getEnvironment();
    String grayEnabled = env.getProperty("gray.enabled");
    if (StringUtils.isEmpty(grayEnabled)) {
        if (ConfigurableEnvironment.class.isInstance(env)) {
            ConfigurableEnvironment environment = (ConfigurableEnvironment) env;
            MutablePropertySources m = environment.getPropertySources();
            Properties p = new Properties();
            p.put("gray.enabled", "true");
            m.addLast(new PropertiesPropertySource("defaultProperties", p));
        }
    }

    return imports;
}
 
Example #7
Source File: AnnotationConditionalOnPropertyBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 6 votes vote down vote up
@Bean
public BeanDefinitionRegistryPostProcessor postProcessor(ConfigurableEnvironment environment) {
    return new BeanDefinitionRegistryPostProcessor() {
        @Override
        public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
            MutablePropertySources propertySources = environment.getPropertySources();
            Map<String, Object> source = new HashMap<>();
            source.put("enabled", "true");
            propertySources.addFirst(new MapPropertySource("for @ConditionalOnProperty", source));
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        }
    };
}
 
Example #8
Source File: WebSocketIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
	this.client = new ReactorNettyWebSocketClient();

	this.server = new ReactorHttpServer();
	this.server.setHandler(createHttpHandler());
	this.server.afterPropertiesSet();
	this.server.start();

	// Set dynamically chosen port
	this.serverPort = this.server.getPort();

	if (this.client instanceof Lifecycle) {
		((Lifecycle) this.client).start();
	}

	this.gatewayContext = new SpringApplicationBuilder(GatewayConfig.class)
			.properties("ws.server.port:" + this.serverPort, "server.port=0",
					"spring.jmx.enabled=false")
			.run();

	ConfigurableEnvironment env = this.gatewayContext
			.getBean(ConfigurableEnvironment.class);
	this.gatewayPort = Integer.valueOf(env.getProperty("local.server.port"));
}
 
Example #9
Source File: H2DbProperties.java    From tx-lcn with Apache License 2.0 6 votes vote down vote up
public H2DbProperties(
        @Autowired(required = false) ConfigurableEnvironment environment,
        @Autowired(required = false) ServerProperties serverProperties) {
    String applicationName = "application";
    Integer port = 0;
    if (Objects.nonNull(environment)) {
        applicationName = environment.getProperty("spring.application.name");
    }
    if (Objects.nonNull(serverProperties)) {
        port = serverProperties.getPort();
    }
    this.filePath = System.getProperty("user.dir") +
            File.separator +
            ".txlcn" +
            File.separator +
            (StringUtils.hasText(applicationName) ? applicationName : "application") +
            "-" + port;
}
 
Example #10
Source File: IntegrationTestConfiguration.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getAllKnownProperties(Environment env) {
    Map<String, String> rtn = new HashMap<>();
    if (env instanceof ConfigurableEnvironment) {
        for (PropertySource<?> propertySource : ((ConfigurableEnvironment) env).getPropertySources()) {
            if (propertySource instanceof EnumerablePropertySource) {
                LOGGER.info("processing property source ::: " + propertySource.getName());
                for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
                    String value = propertySource.getProperty(key).toString();
                    LOGGER.debug("{} = {}", key, value);
                    if (!StringUtils.isEmpty(value) && !rtn.containsKey(key)) {
                        rtn.put(key, propertySource.getProperty(key).toString());
                    }
                }
            }
        }
    }
    return rtn;
}
 
Example #11
Source File: PriceCalculationEnvironmentPostProcessor.java    From tutorials with MIT License 6 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {

    PropertySource<?> system = environment.getPropertySources()
        .get(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);

    Map<String, Object> prefixed = new LinkedHashMap<>();

    if (!hasOurPriceProperties(system)) {
        // Baeldung-internal code so this doesn't break other examples
        logger.warn("System environment variables [calculation_mode,gross_calculation_tax_rate] not detected, fallback to default value [calcuation_mode={},gross_calcuation_tax_rate={}]", CALCUATION_MODE_DEFAULT_VALUE,
            GROSS_CALCULATION_TAX_RATE_DEFAULT_VALUE);
        prefixed = names.stream()
            .collect(Collectors.toMap(this::rename, this::getDefaultValue));
        environment.getPropertySources()
            .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));
        return;
    }

    prefixed = names.stream()
        .collect(Collectors.toMap(this::rename, system::getProperty));
    environment.getPropertySources()
        .addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, new MapPropertySource("prefixer", prefixed));

}
 
Example #12
Source File: SpacedLogbackSystem.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
protected LoggingProperties parseProperties(ConfigurableEnvironment environment) {
    LoggingProperties properties = Binder.get(environment)
            .bind(LoggingProperties.PREFIX, LoggingProperties.class)
            .orElseGet(LoggingProperties::new);

    if (isSet(environment, "trace")) {
        logger.info("debug mode, set default threshold to trace");
        properties.getDefaultSpec().setThreshold("trace");
    } else if (isSet(environment, "debug")) {
        logger.info("debug mode, set default threshold to debug");
        properties.getDefaultSpec().setThreshold("debug");
    } else {
        properties.getDefaultSpec().setThreshold("info");
    }

    return properties;
}
 
Example #13
Source File: SpringApplication.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
private void prepareContext(ConfigurableApplicationContext context,
		ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
		ApplicationArguments applicationArguments, Banner printedBanner) {
	context.setEnvironment(environment);
	postProcessApplicationContext(context);
	applyInitializers(context);
	listeners.contextPrepared(context);
	if (this.logStartupInfo) {
		logStartupInfo(context.getParent() == null);
		logStartupProfileInfo(context);
	}

	// Add boot specific singleton beans
	context.getBeanFactory().registerSingleton("springApplicationArguments",
			applicationArguments);
	if (printedBanner != null) {
		context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);
	}

	// Load the sources
	Set<Object> sources = getAllSources();
	Assert.notEmpty(sources, "Sources must not be empty");
	load(context, sources.toArray(new Object[0]));
	listeners.contextLoaded(context);
}
 
Example #14
Source File: PropertySourceBootstrapConfiguration.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private void handleIncludedProfiles(ConfigurableEnvironment environment) {
	Set<String> includeProfiles = new TreeSet<>();
	for (PropertySource<?> propertySource : environment.getPropertySources()) {
		addIncludedProfilesTo(includeProfiles, propertySource);
	}
	List<String> activeProfiles = new ArrayList<>();
	Collections.addAll(activeProfiles, environment.getActiveProfiles());

	// If it's already accepted we assume the order was set intentionally
	includeProfiles.removeAll(activeProfiles);
	if (includeProfiles.isEmpty()) {
		return;
	}
	// Prepend each added profile (last wins in a property key clash)
	for (String profile : includeProfiles) {
		activeProfiles.add(0, profile);
	}
	environment.setActiveProfiles(
			activeProfiles.toArray(new String[activeProfiles.size()]));
}
 
Example #15
Source File: ManagementEnvironmentCustomizer.java    From Moss with Apache License 2.0 5 votes vote down vote up
private int getManagementPort(ConfigurableEnvironment env) {
    if (!"prod".equalsIgnoreCase(env.getProperty("spring.profiles.active"))) {
        try {
            //不是生产环境,使用Socket去连接如果能连接上表示端口被占用
            InetAddress Address = InetAddress.getByName("127.0.0.1");
            Socket socket = new Socket(Address, SPRINGBOOT_MANAGEMENT_PORT_VALUE);
            logger.info(SPRINGBOOT_MANAGEMENT_PORT_VALUE+":port is used,return:0");
            return 0;
        } catch (IOException e) {
            logger.info(SPRINGBOOT_MANAGEMENT_PORT_VALUE+":port is not used");
        }
    }
    return SPRINGBOOT_MANAGEMENT_PORT_VALUE;
}
 
Example #16
Source File: WireMockApplicationListener.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
private void registerPort(ConfigurableEnvironment environment) {
	Integer httpPortProperty = environment.getProperty("wiremock.server.port",
			Integer.class);
	// If the httpPortProperty is not found it means the AutoConfigureWireMock hasn't
	// been initialised.
	if (httpPortProperty == null) {
		return;
	}
	if (isHttpDynamic(httpPortProperty)) {
		registerPropertySourceForDynamicEntries(environment, "wiremock.server.port",
				10000, 12500, "wiremock.server.port-dynamic");
		if (log.isDebugEnabled()) {
			log.debug("Registered property source for dynamic http port");
		}
	}
	int httpsPortProperty = environment.getProperty("wiremock.server.https-port",
			Integer.class, 0);
	if (isHttpsDynamic(httpsPortProperty)) {
		registerPropertySourceForDynamicEntries(environment,
				"wiremock.server.https-port", 12500, 15000,
				"wiremock.server.https-port-dynamic");
		if (log.isDebugEnabled()) {
			log.debug("Registered property source for dynamic https port");
		}
	}
	else if (httpsPortProperty == -1) {
		MutablePropertySources propertySources = environment.getPropertySources();
		addPropertySource(propertySources);
		Map<String, Object> source = ((MapPropertySource) propertySources
				.get("wiremock")).getSource();
		source.put("wiremock.server.https-port-dynamic", true);
		if (log.isDebugEnabled()) {
			log.debug(
					"Registered property source for dynamic https with https port property set to -1");
		}
	}

}
 
Example #17
Source File: RadarHostInfoEnvironmentPostProcessor.java    From radar with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
	String netCard = environment.getProperty("radar.network.netCard", "");
	LinkedHashMap<String, Object> map = new LinkedHashMap<>();
	// map.put("spring.cloud.client.ipAddress",IPUtil.getLocalIP(getNetCard(environment)));
	if (StringUtils.isEmpty(environment.getProperty("radar.instance.host"))) {
		map.put("spring.cloud.client.ipAddress", IPUtil.getLocalIP(netCard));
	} else {
		map.put("spring.cloud.client.ipAddress", environment.getProperty("radar.instance.host"));
	}
	MapPropertySource propertySource = new MapPropertySource("radarClientHostInfo", map);
	environment.getPropertySources().addLast(propertySource);
}
 
Example #18
Source File: AbstractRefreshableWebApplicationContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>Replace {@code Servlet}-related property sources.
 */
@Override
protected void initPropertySources() {
	ConfigurableEnvironment env = getEnvironment();
	if (env instanceof ConfigurableWebEnvironment) {
		((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
	}
}
 
Example #19
Source File: ApolloApplicationContextInitializerTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
public void testFillFromEnvironmentWithSystemPropertyAlreadyFilled() throws Exception {
  String someAppId = "someAppId";
  String someCluster = "someCluster";
  String someCacheDir = "someCacheDir";
  String someApolloMeta = "someApolloMeta";

  System.setProperty("app.id", someAppId);
  System.setProperty(ConfigConsts.APOLLO_CLUSTER_KEY, someCluster);
  System.setProperty("apollo.cacheDir", someCacheDir);
  System.setProperty(ConfigConsts.APOLLO_META_KEY, someApolloMeta);

  String anotherAppId = "anotherAppId";
  String anotherCluster = "anotherCluster";
  String anotherCacheDir = "anotherCacheDir";
  String anotherApolloMeta = "anotherApolloMeta";

  ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class);

  when(environment.getProperty("app.id")).thenReturn(anotherAppId);
  when(environment.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY)).thenReturn(anotherCluster);
  when(environment.getProperty("apollo.cacheDir")).thenReturn(anotherCacheDir);
  when(environment.getProperty(ConfigConsts.APOLLO_META_KEY)).thenReturn(anotherApolloMeta);

  apolloApplicationContextInitializer.initializeSystemProperty(environment);

  assertEquals(someAppId, System.getProperty("app.id"));
  assertEquals(someCluster, System.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY));
  assertEquals(someCacheDir, System.getProperty("apollo.cacheDir"));
  assertEquals(someApolloMeta, System.getProperty(ConfigConsts.APOLLO_META_KEY));
}
 
Example #20
Source File: ContextInitializer.java    From gluon-samples with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    Cloud cloud = getCloud();

    ConfigurableEnvironment appEnvironment = applicationContext.getEnvironment();

    String[] persistenceProfiles = getCloudProfiles(cloud);
    if (persistenceProfiles == null) {
        persistenceProfiles = new String[] { IN_MEMORY_PROFILE };
    }

    for (String persistenceProfile : persistenceProfiles) {
        appEnvironment.addActiveProfile(persistenceProfile);
    }
}
 
Example #21
Source File: FrameworkServlet.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
	if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
		// The application context id is still set to its original default value
		// -> assign a more useful id based on available information
		if (this.contextId != null) {
			wac.setId(this.contextId);
		}
		else {
			// Generate default id...
			wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
					ObjectUtils.getDisplayString(getServletContext().getContextPath()) + "/" + getServletName());
		}
	}

	wac.setServletContext(getServletContext());
	wac.setServletConfig(getServletConfig());
	wac.setNamespace(getNamespace());
	wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

	// The wac environment's #initPropertySources will be called in any case when the context
	// is refreshed; do it eagerly here to ensure servlet property sources are in place for
	// use in any post-processing or initialization that occurs below prior to #refresh
	ConfigurableEnvironment env = wac.getEnvironment();
	if (env instanceof ConfigurableWebEnvironment) {
		((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
	}

	postProcessWebApplicationContext(wac);
	applyInitializers(wac);
	wac.refresh();
}
 
Example #22
Source File: ApacheCommonsConfigurationEnvironmentPostProcessor.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    try {
        ApacheCommonsConfigurationPropertySource.addToEnvironment(environment,
                new XMLConfiguration("commons-config.xml"));
    } catch (ConfigurationException e) {
        throw new RuntimeException("Unable to load commons-config.xml", e);
    }
}
 
Example #23
Source File: ApacheCommonsConfigurationPropertySource.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
public static void addToEnvironment(ConfigurableEnvironment environment,
                                    XMLConfiguration xmlConfiguration) {
    environment.getPropertySources().addAfter(
            StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
            new ApacheCommonsConfigurationPropertySource(
                    COMMONS_CONFIG_PROPERTY_SOURCE_NAME, xmlConfiguration));
    logger.trace("ApacheCommonsConfigurationPropertySource add to Environment");
}
 
Example #24
Source File: ZipkinStorageConsumerAutoConfiguration.java    From zipkin-sparkstreaming with Apache License 2.0 5 votes vote down vote up
static Properties extractZipkinProperties(ConfigurableEnvironment env) {
  Properties properties = new Properties();
  Iterator<PropertySource<?>> it = env.getPropertySources().iterator();
  while (it.hasNext()) {
    PropertySource<?> next = it.next();
    if (!(next instanceof EnumerablePropertySource)) continue;
    EnumerablePropertySource source = (EnumerablePropertySource) next;
    for (String name : source.getPropertyNames()) {
      if (name.startsWith("zipkin")) properties.put(name, source.getProperty(name));
    }
  }
  return properties;
}
 
Example #25
Source File: C2monApplicationListener.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
  ConfigurableEnvironment environment = event.getEnvironment();
  String propertySource = environment.getProperty("c2mon.client.conf.url");

  if (propertySource != null) {
    try {
      environment.getPropertySources().addAfter("systemEnvironment", new ResourcePropertySource(propertySource));
    } catch (IOException e) {
      throw new RuntimeException("Could not read property source", e);
    }
  }
}
 
Example #26
Source File: ClientSecurityAutoConfigurationUnitTests.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
@Test
public void configuresAuthenticationWithCloudPlatformCredentials() {

	ConfigurableEnvironment environment = spy(new StandardEnvironment());

	Properties vcap = new Properties();

	vcap.setProperty("vcap.application.name", "TestApp");
	vcap.setProperty("vcap.application.uris", "test-app.apps.cloud.skullbox.com");
	vcap.setProperty("vcap.services.test-pcc.name", "test-pcc");
	vcap.setProperty("vcap.services.test-pcc.tags", "pivotal, cloudcache, database, gemfire");
	vcap.setProperty("vcap.services.test-pcc.credentials.users", "Abuser, Master");
	vcap.setProperty("vcap.services.test-pcc.credentials.users[0].username", "Abuser");
	vcap.setProperty("vcap.services.test-pcc.credentials.users[0].password", "p@55w0rd");
	vcap.setProperty("vcap.services.test-pcc.credentials.users[0].roles", "cluster_developer");
	vcap.setProperty("vcap.services.test-pcc.credentials.users[1].username", "Master");
	vcap.setProperty("vcap.services.test-pcc.credentials.users[1].password", "p9@$$w0rd");
	vcap.setProperty("vcap.services.test-pcc.credentials.users[1].roles", "cluster_operator");

	PropertiesPropertySource vcapPropertySource = new PropertiesPropertySource("vcap", vcap);

	environment.getPropertySources().addLast(vcapPropertySource);

	AutoConfiguredCloudSecurityEnvironmentPostProcessor environmentPostProcessor =
		new AutoConfiguredCloudSecurityEnvironmentPostProcessor();

	environmentPostProcessor.configureSecurityContext(environment);

	assertThat(environment.getProperty("spring.data.gemfire.security.username")).isEqualTo("Master");
	assertThat(environment.getProperty("spring.data.gemfire.security.password")).isEqualTo("p9@$$w0rd");

	verify(environment, times(2))
		.containsProperty(eq("spring.data.gemfire.security.username"));

	verify(environment, never())
		.containsProperty(eq("spring.data.gemfire.security.password"));
}
 
Example #27
Source File: NetstrapBootApplication.java    From netstrap with Apache License 2.0 5 votes vote down vote up
/**
 * 装配SpringContext
 * 设置环境,初始化调用,设置监听器
 */
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment) {
    context.setEnvironment(environment);
    applyInitializer(context);
    for (ApplicationListener listener : listeners) {
        context.addApplicationListener(listener);
    }
}
 
Example #28
Source File: DubboDefaultPropertiesEnvironmentPostProcessor.java    From dubbo-spring-boot-project with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    MutablePropertySources propertySources = environment.getPropertySources();
    Map<String, Object> defaultProperties = createDefaultProperties(environment);
    if (!CollectionUtils.isEmpty(defaultProperties)) {
        addOrReplace(propertySources, defaultProperties);
    }
}
 
Example #29
Source File: WallRideInitializer.java    From wallride with Apache License 2.0 5 votes vote down vote up
public static ConfigurableEnvironment createEnvironment(ApplicationStartingEvent event) {
	StandardEnvironment environment = new StandardEnvironment();

	String home = environment.getProperty(WallRideProperties.HOME_PROPERTY);
	if (!StringUtils.hasText(home)) {
		//try to get config-File with wallride.home parameter under webroot
		String configFileHome = getConfigFileHome(event);
		if (configFileHome!=null) {
			home = configFileHome;
		} else {
			throw new IllegalStateException(WallRideProperties.HOME_PROPERTY + " is empty");
		}
	}
	if (!home.endsWith("/")) {
		home = home + "/";
	}

	String config = home + WallRideProperties.DEFAULT_CONFIG_PATH_NAME;
	String media = home + WallRideProperties.DEFAULT_MEDIA_PATH_NAME;

	System.setProperty(WallRideProperties.CONFIG_LOCATION_PROPERTY, config);
	System.setProperty(WallRideProperties.MEDIA_LOCATION_PROPERTY, media);

	event.getSpringApplication().getListeners().stream()
			.filter(listener -> listener.getClass().isAssignableFrom(ConfigFileApplicationListener.class))
			.map(listener -> (ConfigFileApplicationListener) listener)
			.forEach(listener -> listener.setSearchLocations(DEFAULT_CONFIG_SEARCH_LOCATIONS + "," + config));

	return environment;
}
 
Example #30
Source File: AbstractRefreshableWebApplicationContext.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>Replace {@code Servlet}-related property sources.
 */
@Override
protected void initPropertySources() {
	ConfigurableEnvironment env = getEnvironment();
	if (env instanceof ConfigurableWebEnvironment) {
		((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
	}
}