org.springframework.core.env.PropertiesPropertySource Java Examples

The following examples show how to use org.springframework.core.env.PropertiesPropertySource. 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: ExternalizedConfigurationBinderBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) throws IOException {
    // application.properties 文件资源 classpath 路径
    String location = "application.properties";
    // 编码化的 Resource 对象(解决乱码问题)
    EncodedResource resource = new EncodedResource(new ClassPathResource(location), "UTF-8");
    // 加载 application.properties 文件,转化为 Properties 对象
    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    // 创建 Properties 类型的 PropertySource
    PropertiesPropertySource propertySource = new PropertiesPropertySource("map", properties);
    // 转化为 Spring Boot 2 外部化配置源 ConfigurationPropertySource 集合
    Iterable<ConfigurationPropertySource> propertySources = ConfigurationPropertySources.from(propertySource);
    // 创建 Spring Boot 2 Binder 对象(设置 ConversionService ,扩展类型转换能力)
    Binder binder = new Binder(propertySources, null, conversionService());
    // 执行绑定,返回绑定结果
    BindResult<User> bindResult = binder.bind("user", User.class);
    // 获取绑定对象
    User user = bindResult.get();
    // 输出结果
    System.out.println(user);

}
 
Example #2
Source File: FunctionDeployerConfiguration.java    From spring-cloud-function with Apache License 2.0 7 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
String functionName = environment.containsProperty("function.name") ? environment.getProperty("function.name") : null;
	String functionLocation = environment.containsProperty("function.location") ? environment.getProperty("function.location") : null;
	if (StringUtils.hasText(functionName) || StringUtils.hasText(functionLocation)) {
		MutablePropertySources propertySources = environment.getPropertySources();
		propertySources.forEach(ps -> {
			if (ps instanceof PropertiesPropertySource) {
				((MapPropertySource) ps).getSource().put(FunctionProperties.PREFIX + ".definition", functionName);
				((MapPropertySource) ps).getSource().put(FunctionProperties.PREFIX + ".location", functionLocation);
			}
		});
	}
}
 
Example #3
Source File: MicrometerSpringApplicationRunListener.java    From summerframework with Apache License 2.0 7 votes vote down vote up
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
    new TransactionManagerCustomizer().apply(environment);
    if (environment.getProperty(METRICS_INFLUX_ENABLED) == null) {
        logger.info("{} not set. Default enable", METRICS_INFLUX_ENABLED);
        Properties props = createProperties(environment);
        logger.info("summerframeworkMicrometer = {}", props);
        environment.getPropertySources().addLast(new PropertiesPropertySource("summerframeworkMicrometer", props));
    }
}
 
Example #4
Source File: PropertiesListener.java    From TarsJava with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
    RemotePropertySource sources = event.getSpringApplication()
            .getMainApplicationClass().getAnnotation(RemotePropertySource.class);

    String configPath = Server.getInstance().getServerConfig().getBasePath() + "/conf/";
    if (sources != null) {
        for (String name : sources.value()) {
            try {
                ConfigHelper.getInstance().loadConfig(name);
                File config = new File(configPath + name);

                if (config.exists()) {
                    Properties properties = new Properties();
                    properties.load(new FileInputStream(config));
                    event.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource(name, properties));
                } else {
                    throw new RuntimeException("[TARS] load config failed file not exists");
                }
            } catch (IOException e) {
                System.err.println("[TARS] load config failed: " + name);
                e.printStackTrace();
            }
        }
    }
}
 
Example #5
Source File: IbisApplicationInitializer.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext) {
	System.setProperty(EndpointImpl.CHECK_PUBLISH_ENDPOINT_PERMISSON_PROPERTY_WITH_SECURITY_MANAGER, "false");
	servletContext.log("Starting IBIS WebApplicationInitializer");

	XmlWebApplicationContext applicationContext = new XmlWebApplicationContext();
	applicationContext.setConfigLocation(XmlWebApplicationContext.CLASSPATH_URL_PREFIX + "/webApplicationContext.xml");
	applicationContext.setDisplayName("IbisApplicationInitializer");

	MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
	propertySources.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
	propertySources.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
	propertySources.addFirst(new PropertiesPropertySource("ibis", AppConstants.getInstance()));

	return applicationContext;
}
 
Example #6
Source File: CCPropertySourceLoader.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
public PropertySource<?> load(String name, Resource resource, String profile) throws IOException {

		logger.info("load PropertySource -> name:{},profile:{}", name, profile);
		if (profile == null) {
			Properties properties = loadProperties(name,resource);
			if (profiles == null) {
				profiles = properties.getProperty("spring.profiles.active");
			} else {
				logger.info("spring.profiles.active = " + profiles + ",ignore load remote config");
			}
			// 如果指定了profile,则也不加载远程配置
			if (profiles == null && ccContext.isRemoteEnabled() && !ccContext.isProcessed()) {
				ccContext.init(properties, true);
				ccContext.mergeRemoteProperties(properties);
			}

			if (!properties.isEmpty()) {
				return new PropertiesPropertySource(name, properties);
			}
		}
		return null;
	}
 
Example #7
Source File: CCPropertySourceLoader.java    From jeesuite-config with Apache License 2.0 6 votes vote down vote up
public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
	Properties properties =  loadProperties(name,resource);
	if (profiles == null) {
		profiles = properties.getProperty("spring.profiles.active");
	} else {
		logger.info("spring.profiles.active = " + profiles + ",ignore load remote config");
	}
	// 如果指定了profile,则也不加载远程配置
	if (profiles == null && ccContext.isRemoteEnabled() && !ccContext.isProcessed()) {
		ccContext.init(properties, true);
		ccContext.mergeRemoteProperties(properties);
		PropertySource<?> props = new PropertiesPropertySource(ConfigcenterContext.MANAGER_PROPERTY_SOURCE, properties);
		return Arrays.asList(props);
	}
	
	return new ArrayList<>();
}
 
Example #8
Source File: CustomMybatisMapperConfigurationTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
private AnnotationConfigApplicationContext context(Class<?>... clzz) throws Exception {
    AnnotationConfigApplicationContext annotationConfigApplicationContext
            = new AnnotationConfigApplicationContext();
    annotationConfigApplicationContext.register(clzz);

    URL propertiesUrl = this.getClass().getClassLoader().getResource("config/application.properties");
    File springBootPropertiesFile = new File(propertiesUrl.toURI());
    Properties springBootProperties = new Properties();
    springBootProperties.load(new FileInputStream(springBootPropertiesFile));

    annotationConfigApplicationContext
            .getEnvironment()
            .getPropertySources()
            .addFirst(new PropertiesPropertySource("testProperties", springBootProperties));

    annotationConfigApplicationContext.refresh();
    return annotationConfigApplicationContext;
}
 
Example #9
Source File: CrossOriginTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setup() {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	Properties props = new Properties();
	props.setProperty("myOrigin", "http://example.com");
	wac.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("ps", props));
	wac.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class);
	wac.refresh();

	this.handlerMapping.setRemoveSemicolonContent(false);
	wac.getAutowireCapableBeanFactory().initializeBean(this.handlerMapping, "hm");

	this.request.setMethod("GET");
	this.request.addHeader(HttpHeaders.ORIGIN, "http://domain.com/");
}
 
Example #10
Source File: CloudWatchPropertiesTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void properties_set_shouldOverrideValues() {
	Properties properties = new Properties();
	properties.setProperty("management.metrics.export.cloudwatch.namespace", "test");
	properties.setProperty("management.metrics.export.cloudwatch.batch-size", "5");

	AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
	applicationContext.getEnvironment().getPropertySources()
			.addLast(new PropertiesPropertySource("test", properties));
	applicationContext.register(CloudWatchPropertiesConfiguration.class);
	applicationContext.refresh();

	CloudWatchProperties cloudWatchProperties = applicationContext
			.getBean(CloudWatchProperties.class);
	assertThat(cloudWatchProperties.getNamespace()).isEqualTo("test");
	assertThat(cloudWatchProperties.getBatchSize()).isEqualTo(5);
}
 
Example #11
Source File: DispatcherWebscript.java    From alfresco-mvc with Apache License 2.0 6 votes vote down vote up
protected void configureDispatcherServlet(DispatcherServlet dispatcherServlet) {
	if (inheritGlobalProperties) {
		final Properties globalProperties = (Properties) this.applicationContext.getBean("global-properties");

		ConfigurableEnvironment servletEnv = dispatcherServlet.getEnvironment();
		servletEnv.merge(new AbstractEnvironment() {
			@Override
			public MutablePropertySources getPropertySources() {
				MutablePropertySources mutablePropertySources = new MutablePropertySources();
				mutablePropertySources
						.addFirst(new PropertiesPropertySource("alfresco-global.properties", globalProperties));
				return mutablePropertySources;
			}
		});
	}
}
 
Example #12
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 #13
Source File: PlatformMybatisApplicationRunListener.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
    Properties props = new Properties();

    if (environment.containsProperty(MYBATIS_ENCRYPT_PASSWORD)) {
        System.setProperty(MYBATIS_ENCRYPT_PASSWORD, environment.getProperty(MYBATIS_ENCRYPT_PASSWORD));
    }

    if (environment.containsProperty(MYBATIS_ENCRYPT_SALT)) {
        System.setProperty(MYBATIS_ENCRYPT_SALT, environment.getProperty(MYBATIS_ENCRYPT_SALT));
    }

    if (environment.containsProperty(SHA1_COLUMN_HANDLER_SALT)) {
        System.setProperty(SHA1_COLUMN_HANDLER_SALT, environment.getProperty(SHA1_COLUMN_HANDLER_SALT));
    }
    if (environment.containsProperty(MYBATIS_TYPE_HANDLERS_PACKAGE)) {
        props.put(MYBATIS_TYPE_HANDLERS_PACKAGE,
            environment.getProperty(MYBATIS_TYPE_HANDLERS_PACKAGE) + "," + MYBATIS_TYPE_HANDLERS_PACKAGE_VALUE);
    } else {
        props.put(MYBATIS_TYPE_HANDLERS_PACKAGE, MYBATIS_TYPE_HANDLERS_PACKAGE_VALUE);
    }
    environment.getPropertySources().addFirst(new PropertiesPropertySource("summerframeworkMybatis", props));
}
 
Example #14
Source File: IngestXmlPSC.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
    * {@inheritDoc}
    *
    * <p>
    * Here we combine all properties, making sure that the Rice project properties go in last.
    * </p>
    */
@Override
@Bean
public PropertySource<?> propertySource() {
	List<Location> locations = Lists.newArrayList();

	locations.addAll(jdbcConfig.jdbcPropertyLocations());
	locations.addAll(sourceSqlConfig.riceSourceSqlPropertyLocations());
	locations.addAll(ingestXmlConfig.riceIngestXmlPropertyLocations());

	Properties properties = service.getProperties(locations);

	String location = ProjectUtils.getPath(RiceXmlProperties.APP.getResource());
	Config riceConfig = RiceConfigUtils.parseAndInit(location);
	RiceConfigUtils.putProperties(riceConfig, properties);

	return new PropertiesPropertySource("properties", riceConfig.getProperties());
}
 
Example #15
Source File: DefinitionPropertySourceFactory.java    From seppb with MIT License 6 votes vote down vote up
/**
 * 从外部获取配置文件,并对加密后的数据库用户名和密码做解密
 *
 * @param environment
 * @param application
 */
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    String configPath = environment.getProperty("path");
    if (Env.getCurrentEnv() == LOCAL) {
        eagerLoad(environment);
        return;
    }
    File file = new File(defaultIfBlank(configPath, "/opt/sqcs_backend/spring.properties"));
    log.info("configPath:{}", configPath);
    try (InputStream input = new FileInputStream(file)) {
        Properties properties = buildDecryptProperties(input);
        PropertiesPropertySource propertySource = new PropertiesPropertySource("spring", properties);
        environment.getPropertySources().addLast(propertySource);
    } catch (Exception e) {
        throw new SeppServerException("配置文件读取错误", e);
    }
}
 
Example #16
Source File: MybatisplusApplicationRunListener.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
    Properties props = new Properties();
    if (!environment.containsProperty(ID_TYPE)) {

        props.put(ID_TYPE, ID_TYPE_AUTO);
    }

    if (environment.containsProperty(MYBATIS_TYPE_HANDLERS_PACKAGE)) {
        props.put(MYBATIS_TYPE_HANDLERS_PACKAGE,
            environment.getProperty(MYBATIS_TYPE_HANDLERS_PACKAGE) + "," + MYBATIS_TYPE_HANDLERS_PACKAGE_VALUE);
    } else {
        props.put(MYBATIS_TYPE_HANDLERS_PACKAGE, MYBATIS_TYPE_HANDLERS_PACKAGE_VALUE);
    }
    environment.getPropertySources().addFirst(new PropertiesPropertySource("summerframeworkMybatisplus", props));
}
 
Example #17
Source File: CrossOriginTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Before
@SuppressWarnings("resource")
public void setup() {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	Properties props = new Properties();
	props.setProperty("myOrigin", "https://example.com");
	wac.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("ps", props));
	wac.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class);
	wac.refresh();

	this.handlerMapping.setRemoveSemicolonContent(false);
	wac.getAutowireCapableBeanFactory().initializeBean(this.handlerMapping, "hm");

	this.request.setMethod("GET");
	this.request.addHeader(HttpHeaders.ORIGIN, "https://domain.com/");
}
 
Example #18
Source File: PropertiesLogger.java    From SO with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private List<PropertiesPropertySource> findPropertiesPropertySources() {
    List<PropertiesPropertySource> propertiesPropertySources = new LinkedList<>();
    for (PropertySource<?> propertySource : environment.getPropertySources()) {
        if (propertySource instanceof PropertiesPropertySource) {
            propertiesPropertySources.add((PropertiesPropertySource) propertySource);
        }
    }
    return propertiesPropertySources;
}
 
Example #19
Source File: PropertiesLogger.java    From SO with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@PostConstruct
public void printProperties() {

    log.info("**** APPLICATION PROPERTIES SOURCES ****");

    Set<String> properties = new TreeSet<>();
    for (PropertiesPropertySource p : findPropertiesPropertySources()) {
        log.info(p.toString());
        properties.addAll(Arrays.asList(p.getPropertyNames()));
    }

    log.info("**** APPLICATION PROPERTIES VALUES ****");
    print(properties);

}
 
Example #20
Source File: ParamStorePropertySourcePostProcessor.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) throws BeansException {
    final Properties propertiesSource = new Properties();

    final GetParametersByPathRequest.Builder requestBuilder = GetParametersByPathRequest
            .builder()
            .path(properties.getPath())
            .recursive(true)
            .withDecryption(true);

    final GetParametersByPathResponse firstPage = ssmClient.getParametersByPath(requestBuilder.build());
    addParametersToPropertiesSource(propertiesSource, firstPage.parameters());
    String nextToken = firstPage.nextToken();

    while (!isNullOrEmpty(nextToken)) {
        final GetParametersByPathResponse nextPage = ssmClient.getParametersByPath(requestBuilder
                .nextToken(nextToken)
                .build()
        );
        addParametersToPropertiesSource(propertiesSource, nextPage.parameters());
        nextToken = nextPage.nextToken();
    }

    final ConfigurableEnvironment env = beanFactory.getBean(ConfigurableEnvironment.class);
    final MutablePropertySources propertySources = env.getPropertySources();
    if (properties.isAddWithLowestPrecedence()) {
        propertySources.addLast(new PropertiesPropertySource(PARAMETER_STORE_PROPERTY_SOURCE, propertiesSource));
    } else {
        propertySources.addFirst(new PropertiesPropertySource(PARAMETER_STORE_PROPERTY_SOURCE, propertiesSource));
    }
}
 
Example #21
Source File: PropertyMaskingContextInitializer.java    From spring-cloud-services-connector with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
	ConfigurableEnvironment environment = applicationContext.getEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();

	String[] defaultKeys = {"password", "secret", "key", "token", ".*credentials.*", "vcap_services"};
	Set<String> propertiesToSanitize = Stream.of(defaultKeys)
											 .collect(Collectors.toSet());

	PropertySource<?> bootstrapProperties = propertySources.get(BOOTSTRAP_PROPERTY_SOURCE_NAME);
	Set<PropertySource<?>> bootstrapNestedPropertySources = new HashSet<>();
	Set<PropertySource<?>> configServiceNestedPropertySources = new HashSet<>();

	if (bootstrapProperties != null && bootstrapProperties instanceof CompositePropertySource) {
		bootstrapNestedPropertySources.addAll(((CompositePropertySource) bootstrapProperties).getPropertySources());
	}
	for (PropertySource<?> nestedProperty : bootstrapNestedPropertySources) {
		if (nestedProperty.getName().equals(CONFIG_SERVICE_PROPERTY_SOURCE_NAME)) {
			configServiceNestedPropertySources.addAll(((CompositePropertySource) nestedProperty).getPropertySources());
		}
	}

	Stream<String> vaultKeyNameStream =
			configServiceNestedPropertySources.stream()
											  .filter(ps -> ps instanceof EnumerablePropertySource)
											  .filter(ps -> ps.getName().startsWith(VAULT_PROPERTY_PATTERN) || ps.getName().startsWith(CREDHUB_PROPERTY_PATTERN))
											  .map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
											  .flatMap(Arrays::<String>stream);

	propertiesToSanitize.addAll(vaultKeyNameStream.collect(Collectors.toSet()));

	PropertiesPropertySource envKeysToSanitize =
			new PropertiesPropertySource(
					SANITIZE_ENV_KEY, mergeClientProperties(propertySources, propertiesToSanitize));

	environment.getPropertySources().addFirst(envKeysToSanitize);
	applicationContext.setEnvironment(environment);

}
 
Example #22
Source File: PropertiesInvalidInputTest.java    From code-examples with MIT License 5 votes vote down vote up
@BeforeEach
void setup() {
    // create Spring Application dynamically
    application = new SpringApplication(ValidationApplication.class);

    // setting test properties for our Spring Application
    properties = new Properties();

    ConfigurableEnvironment environment = new StandardEnvironment();
    MutablePropertySources propertySources = environment.getPropertySources();
    propertySources.addFirst(new PropertiesPropertySource("application-test", properties));
    application.setEnvironment(environment);
}
 
Example #23
Source File: PropertiesLogger.java    From SO with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private List<PropertiesPropertySource> findPropertiesPropertySources() {
    List<PropertiesPropertySource> propertiesPropertySources = new LinkedList<>();
    for (PropertySource<?> propertySource : environment.getPropertySources()) {
        if (propertySource instanceof PropertiesPropertySource) {
            propertiesPropertySources.add((PropertiesPropertySource) propertySource);
        }
    }
    return propertiesPropertySources;
}
 
Example #24
Source File: PropertySourcesPlaceholderConfigurer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>Processing occurs by replacing ${...} placeholders in bean definitions by resolving each
 * against this configurer's set of {@link PropertySources}, which includes:
 * <ul>
 * <li>all {@linkplain org.springframework.core.env.ConfigurableEnvironment#getPropertySources
 * environment property sources}, if an {@code Environment} {@linkplain #setEnvironment is present}
 * <li>{@linkplain #mergeProperties merged local properties}, if {@linkplain #setLocation any}
 * {@linkplain #setLocations have} {@linkplain #setProperties been}
 * {@linkplain #setPropertiesArray specified}
 * <li>any property sources set by calling {@link #setPropertySources}
 * </ul>
 * <p>If {@link #setPropertySources} is called, <strong>environment and local properties will be
 * ignored</strong>. This method is designed to give the user fine-grained control over property
 * sources, and once set, the configurer makes no assumptions about adding additional sources.
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	if (this.propertySources == null) {
		this.propertySources = new MutablePropertySources();
		if (this.environment != null) {
			this.propertySources.addLast(
				new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
					@Override
					public String getProperty(String key) {
						return this.source.getProperty(key);
					}
				}
			);
		}
		try {
			PropertySource<?> localPropertySource =
					new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
			if (this.localOverride) {
				this.propertySources.addFirst(localPropertySource);
			}
			else {
				this.propertySources.addLast(localPropertySource);
			}
		}
		catch (IOException ex) {
			throw new BeanInitializationException("Could not load properties", ex);
		}
	}

	processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
	this.appliedPropertySources = this.propertySources;
}
 
Example #25
Source File: CamundaBpmVersion.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
public PropertiesPropertySource getPropertiesPropertySource() {
  final Properties props = new Properties();
  props.put(key(VERSION), version);
  props.put(key(IS_ENTERPRISE), isEnterprise);
  props.put(key(FORMATTED_VERSION), formattedVersion);

  return new PropertiesPropertySource(this.getClass().getSimpleName(), props);
}
 
Example #26
Source File: PropertyMaskingContextInitializer.java    From spring-cloud-services-starters with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
	ConfigurableEnvironment environment = applicationContext.getEnvironment();
	MutablePropertySources propertySources = environment.getPropertySources();

	String[] defaultKeys = { "password", "secret", "key", "token", ".*credentials.*", "vcap_services" };
	Set<String> propertiesToSanitize = Stream.of(defaultKeys).collect(Collectors.toSet());

	PropertySource<?> bootstrapProperties = propertySources.get(BOOTSTRAP_PROPERTY_SOURCE_NAME);
	Set<PropertySource<?>> bootstrapNestedPropertySources = new HashSet<>();
	Set<PropertySource<?>> configServiceNestedPropertySources = new HashSet<>();

	if (bootstrapProperties != null && bootstrapProperties instanceof CompositePropertySource) {
		bootstrapNestedPropertySources.addAll(((CompositePropertySource) bootstrapProperties).getPropertySources());
	}
	for (PropertySource<?> nestedProperty : bootstrapNestedPropertySources) {
		if (nestedProperty.getName().equals(CONFIG_SERVICE_PROPERTY_SOURCE_NAME)) {
			configServiceNestedPropertySources
					.addAll(((CompositePropertySource) nestedProperty).getPropertySources());
		}
	}

	Stream<String> vaultKeyNameStream = configServiceNestedPropertySources.stream()
			.filter(ps -> ps instanceof EnumerablePropertySource)
			.filter(ps -> ps.getName().startsWith(VAULT_PROPERTY_PATTERN)
					|| ps.getName().startsWith(CREDHUB_PROPERTY_PATTERN))
			.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames()).flatMap(Arrays::<String>stream);

	propertiesToSanitize.addAll(vaultKeyNameStream.collect(Collectors.toSet()));

	PropertiesPropertySource envKeysToSanitize = new PropertiesPropertySource(SANITIZE_ENV_KEY,
			mergeClientProperties(propertySources, propertiesToSanitize));

	environment.getPropertySources().addFirst(envKeysToSanitize);
	applicationContext.setEnvironment(environment);

}
 
Example #27
Source File: YamlPropertySourceFactory.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public PropertySource<?> createPropertySource(@Nullable String name, @Nonnull EncodedResource resource)
        throws IOException {

    final String sourceName = name != null ? name : resource.getResource().getFilename();
    if (sourceName == null) {
        throw new IllegalArgumentException("Resource does not have a filename");
    }

    final Properties propertiesFromYaml = loadYamlIntoProperties(resource);
    return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
 
Example #28
Source File: XsuaaServicePropertySourceFactory.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a PropertySource object for a map of xsuaa properties.
 *
 * @param name
 *            of the propertySource. Use only "xsuaa" as name in case you like
 *            to overwrite/set all properties.
 * @param properties
 *            map of xsuaa properties.
 * @return created @Code{PropertySource}
 */
public static PropertySource create(String name, Properties properties) {
	for (final String property : properties.stringPropertyNames()) {
		if (XSUAA_ATTRIBUTES.contains(property)) {
			properties.setProperty(XSUAA_PREFIX + property, properties.remove(property).toString());
		} else {
			logger.info("Property {} is not considered as part of PropertySource.", property);
		}
	}
	return new PropertiesPropertySource(name, properties);
}
 
Example #29
Source File: PropertySourcesPlaceholderConfigurer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Processing occurs by replacing ${...} placeholders in bean definitions by resolving each
 * against this configurer's set of {@link PropertySources}, which includes:
 * <ul>
 * <li>all {@linkplain org.springframework.core.env.ConfigurableEnvironment#getPropertySources
 * environment property sources}, if an {@code Environment} {@linkplain #setEnvironment is present}
 * <li>{@linkplain #mergeProperties merged local properties}, if {@linkplain #setLocation any}
 * {@linkplain #setLocations have} {@linkplain #setProperties been}
 * {@linkplain #setPropertiesArray specified}
 * <li>any property sources set by calling {@link #setPropertySources}
 * </ul>
 * <p>If {@link #setPropertySources} is called, <strong>environment and local properties will be
 * ignored</strong>. This method is designed to give the user fine-grained control over property
 * sources, and once set, the configurer makes no assumptions about adding additional sources.
 */
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	if (this.propertySources == null) {
		this.propertySources = new MutablePropertySources();
		if (this.environment != null) {
			this.propertySources.addLast(
				new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
					@Override
					@Nullable
					public String getProperty(String key) {
						return this.source.getProperty(key);
					}
				}
			);
		}
		try {
			PropertySource<?> localPropertySource =
					new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
			if (this.localOverride) {
				this.propertySources.addFirst(localPropertySource);
			}
			else {
				this.propertySources.addLast(localPropertySource);
			}
		}
		catch (IOException ex) {
			throw new BeanInitializationException("Could not load properties", ex);
		}
	}

	processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
	this.appliedPropertySources = this.propertySources;
}
 
Example #30
Source File: YamlPropertySourceFactory.java    From spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    log.info("name is {}, resource is {}", name, resource);
    Properties propertiesFromYaml = loadYamlIntoProperties(resource);
    String sourceName = name != null ? name : resource.getResource().getFilename();
    log.info("sourceName is {}", sourceName);
    return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}