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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: FlowableLiquibaseEnvironmentPostProcessor.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    String liquibaseProperty = getLiquibaseProperty();
    if (!environment.containsProperty(liquibaseProperty)) {
        LOGGER.warn("Liquibase has not been explicitly enabled or disabled. Overriding default from Spring Boot from `true` to `false`. "
            + "Flowable pulls in Liquibase, but does not use the Spring Boot configuration for it. "
            + "If you are using it you would need to set `{}` to `true` by yourself", liquibaseProperty);
        Map<String, Object> source = new HashMap<>();
        source.put(liquibaseProperty, false);
        environment.getPropertySources().addLast(new MapPropertySource("flowable-liquibase-override", source));
    }
}
 
Example #16
Source File: AnnotationConfigApplicationContext.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Propagates the given custom {@code Environment} to the underlying
 * {@link AnnotatedBeanDefinitionReader} and {@link ClassPathBeanDefinitionScanner}.
 */
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
	super.setEnvironment(environment);
	this.reader.setEnvironment(environment);
	this.scanner.setEnvironment(environment);
}
 
Example #17
Source File: ConfigMapPropertySourceLocator.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Override
public MapPropertySource locate(Environment environment) {
    if (environment instanceof ConfigurableEnvironment) {
        ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
        String name = getApplicationName(environment, properties);
        String namespace = getApplicationNamespace(client, env, properties);
        return new ConfigMapPropertySource(client, name, namespace);
    }
    return null;
}
 
Example #18
Source File: ApolloSpringApplicationRunListener.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@Override
public void environmentPrepared(ConfigurableEnvironment env) {
    Properties props = new Properties();
    props.put(APOLLO_BOOTSTRAP_ENABLE_KEY, true);
    System.setProperty("spring.banner.location", "classpath:META-INF/banner.txt");
    env.getPropertySources().addFirst(new PropertiesPropertySource("apolloConfig", props));
    // 初始化环境
    this.initEnv(env);
    // 初始化appId
    this.initAppId(env);
    // 初始化架构提供的默认配置
    this.initInfraConfig(env);
}
 
Example #19
Source File: HttpServletBean.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return the {@link Environment} associated with this servlet.
 * <p>If none specified, a default environment will be initialized via
 * {@link #createEnvironment()}.
 */
@Override
public ConfigurableEnvironment getEnvironment() {
	if (this.environment == null) {
		this.environment = createEnvironment();
	}
	return this.environment;
}
 
Example #20
Source File: ExtendPropertySourcesRunListener.java    From thinking-in-spring-boot-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
    // 从 ConfigurableApplicationContext 获取 ConfigurableEnvironment
    ConfigurableEnvironment environment = context.getEnvironment();
    MutablePropertySources propertySources = environment.getPropertySources();
    // 通过名称获取名为 "systemProperties" 的 PropertySource(实现使用常量)
    PropertySource propertySource = propertySources.get(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
    // 将 "systemProperties" 的 PropertySource 添加在 "contextPrepared" 之前(由 contextPrepared 方法添加),提高优先级
    propertySources.addBefore("contextPrepared", propertySource);
}
 
Example #21
Source File: DisableEndpointPostProcessor.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
private void disableEndpoint(final ConfigurableListableBeanFactory beanFactory) {
    final ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class);
    final MutablePropertySources propertySources = env.getPropertySources();
    propertySources.addFirst(
            new MapPropertySource(endpoint + "PropertySource", singletonMap("endpoints." + endpoint + ".enabled", false))
    );
}
 
Example #22
Source File: EnvironmentPreparedEventApplicationListener.java    From micro-service with MIT License 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
	
	ConfigurableEnvironment environment = event.getEnvironment();
	
	for(Iterator<PropertySource<?>> it = environment.getPropertySources().iterator();it.hasNext();) {
		PropertySource<?> propertySource = it.next();
		getPropertiesFromSource(propertySource);
	}
	
	logger.info("2 Enviroment准备完毕,  EnvironmentPreparedEventApplicationListener...");
}
 
Example #23
Source File: EnvironmentRepositoryConfiguration.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Bean
public MultipleJGitEnvironmentRepositoryFactory gitEnvironmentRepositoryFactory(
		ConfigurableEnvironment environment, ConfigServerProperties server,
		Optional<ConfigurableHttpConnectionFactory> jgitHttpConnectionFactory,
		Optional<TransportConfigCallback> customTransportConfigCallback,
		Optional<GoogleCloudSourceSupport> googleCloudSourceSupport) {
	final TransportConfigCallbackFactory transportConfigCallbackFactory = new TransportConfigCallbackFactory(
			customTransportConfigCallback.orElse(null),
			googleCloudSourceSupport.orElse(null));
	return new MultipleJGitEnvironmentRepositoryFactory(environment, server,
			jgitHttpConnectionFactory, transportConfigCallbackFactory);
}
 
Example #24
Source File: EnableDiscoveryClientImportSelector.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Override
public String[] selectImports(AnnotationMetadata metadata) {
	String[] imports = super.selectImports(metadata);

	AnnotationAttributes attributes = AnnotationAttributes.fromMap(
			metadata.getAnnotationAttributes(getAnnotationClass().getName(), true));

	boolean autoRegister = attributes.getBoolean("autoRegister");

	if (autoRegister) {
		List<String> importsList = new ArrayList<>(Arrays.asList(imports));
		importsList.add(
				"org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration");
		imports = importsList.toArray(new String[0]);
	}
	else {
		Environment env = getEnvironment();
		if (ConfigurableEnvironment.class.isInstance(env)) {
			ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env;
			LinkedHashMap<String, Object> map = new LinkedHashMap<>();
			map.put("spring.cloud.service-registry.auto-registration.enabled", false);
			MapPropertySource propertySource = new MapPropertySource(
					"springCloudDiscoveryClient", map);
			configEnv.getPropertySources().addLast(propertySource);
		}

	}

	return imports;
}
 
Example #25
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);
	}
}
 
Example #26
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 #27
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 #28
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 #29
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 #30
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", "[email protected]");
	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", "[email protected]$$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("[email protected]$$w0rd");

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

	verify(environment, never())
		.containsProperty(eq("spring.data.gemfire.security.password"));
}