org.springframework.core.env.CompositePropertySource Java Examples

The following examples show how to use org.springframework.core.env.CompositePropertySource. 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: PropertySourceLocator.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
static Collection<PropertySource<?>> locateCollection(PropertySourceLocator locator,
		Environment environment) {
	PropertySource<?> propertySource = locator.locate(environment);
	if (propertySource == null) {
		return Collections.emptyList();
	}
	if (CompositePropertySource.class.isInstance(propertySource)) {
		Collection<PropertySource<?>> sources = ((CompositePropertySource) propertySource)
				.getPropertySources();
		List<PropertySource<?>> filteredSources = new ArrayList<>();
		for (PropertySource<?> p : sources) {
			if (p != null) {
				filteredSources.add(p);
			}
		}
		return filteredSources;
	}
	else {
		return Arrays.asList(propertySource);
	}
}
 
Example #2
Source File: VaultPropertySourceLocatorUnitTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLocatePropertySourcesInVaultApplicationContext() {

	VaultKeyValueBackendProperties backendProperties = new VaultKeyValueBackendProperties();
	backendProperties.setApplicationName("wintermute");
	backendProperties.setProfiles(Arrays.asList("vermillion", "periwinkle"));

	this.propertySourceLocator = new VaultPropertySourceLocator(this.operations,
			new VaultProperties(),
			VaultPropertySourceLocatorSupport.createConfiguration(backendProperties));

	PropertySource<?> propertySource = this.propertySourceLocator
			.locate(this.configurableEnvironment);

	assertThat(propertySource).isInstanceOf(CompositePropertySource.class);

	CompositePropertySource composite = (CompositePropertySource) propertySource;
	assertThat(composite.getPropertySources()).extracting("name").containsSequence(
			"secret/wintermute/periwinkle", "secret/wintermute/vermillion",
			"secret/wintermute");
}
 
Example #3
Source File: VaultPropertySourceLocatorUnitTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLocatePropertySourcesInEachPathSpecifiedWhenApplicationNameContainsSeveral() {

	VaultKeyValueBackendProperties backendProperties = new VaultKeyValueBackendProperties();
	backendProperties.setApplicationName("wintermute,straylight,icebreaker/armitage");
	backendProperties.setProfiles(Arrays.asList("vermillion", "periwinkle"));

	this.propertySourceLocator = new VaultPropertySourceLocator(this.operations,
			new VaultProperties(),
			VaultPropertySourceLocatorSupport.createConfiguration(backendProperties));

	PropertySource<?> propertySource = this.propertySourceLocator
			.locate(this.configurableEnvironment);

	assertThat(propertySource).isInstanceOf(CompositePropertySource.class);

	CompositePropertySource composite = (CompositePropertySource) propertySource;
	assertThat(composite.getPropertySources()).extracting("name").contains(
			"secret/wintermute", "secret/straylight", "secret/icebreaker/armitage",
			"secret/wintermute/vermillion", "secret/wintermute/periwinkle",
			"secret/straylight/vermillion", "secret/straylight/periwinkle",
			"secret/icebreaker/armitage/vermillion",
			"secret/icebreaker/armitage/periwinkle");
}
 
Example #4
Source File: VaultPropertySourceLocatorUnitTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreatePropertySourcesInOrder() {

	DefaultSecretBackendConfigurer configurer = new DefaultSecretBackendConfigurer();
	configurer.add(new MySecondSecretBackendMetadata());
	configurer.add(new MyFirstSecretBackendMetadata());

	this.propertySourceLocator = new VaultPropertySourceLocator(this.operations,
			new VaultProperties(), configurer);

	PropertySource<?> propertySource = this.propertySourceLocator
			.locate(this.configurableEnvironment);

	assertThat(propertySource).isInstanceOf(CompositePropertySource.class);

	CompositePropertySource composite = (CompositePropertySource) propertySource;
	assertThat(composite.getPropertySources()).extracting("name")
			.containsSequence("foo", "bar");
}
 
Example #5
Source File: NacosPropertySourceLocator.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
/**
 * load configuration of application.
 */
private void loadApplicationConfiguration(
		CompositePropertySource compositePropertySource, String dataIdPrefix,
		NacosConfigProperties properties, Environment environment) {
	String fileExtension = properties.getFileExtension();
	String nacosGroup = properties.getGroup();
	// load directly once by default
	loadNacosDataIfPresent(compositePropertySource, dataIdPrefix, nacosGroup,
			fileExtension, true);
	// load with suffix, which have a higher priority than the default
	loadNacosDataIfPresent(compositePropertySource,
			dataIdPrefix + DOT + fileExtension, nacosGroup, fileExtension, true);
	// Loaded with profile, which have a higher priority than the suffix
	for (String profile : environment.getActiveProfiles()) {
		String dataId = dataIdPrefix + SEP1 + profile + DOT + fileExtension;
		loadNacosDataIfPresent(compositePropertySource, dataId, nacosGroup,
				fileExtension, true);
	}

}
 
Example #6
Source File: EncryptablePropertySourceBeanFactoryPostProcessor.java    From jasypt-spring-boot with MIT License 6 votes vote down vote up
private PropertySource createPropertySource(AnnotationAttributes attributes, ConfigurableEnvironment environment, ResourceLoader resourceLoader, EncryptablePropertyResolver resolver, EncryptablePropertyFilter propertyFilter, List<PropertySourceLoader> loaders) throws Exception {
    String name = generateName(attributes.getString("name"));
    String[] locations = attributes.getStringArray("value");
    boolean ignoreResourceNotFound = attributes.getBoolean("ignoreResourceNotFound");
    CompositePropertySource compositePropertySource = new CompositePropertySource(name);
    Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
    for (String location : locations) {
        String resolvedLocation = environment.resolveRequiredPlaceholders(location);
        Resource resource = resourceLoader.getResource(resolvedLocation);
        if (!resource.exists()) {
            if (!ignoreResourceNotFound) {
                throw new IllegalStateException(String.format("Encryptable Property Source '%s' from location: %s Not Found", name, resolvedLocation));
            } else {
                log.info("Ignoring NOT FOUND Encryptable Property Source '{}' from locations: {}", name, resolvedLocation);
            }
        } else {
            String actualName = name + "#" + resolvedLocation;
            loadPropertySource(loaders, resource, actualName)
                    .ifPresent(psources -> psources.forEach(compositePropertySource::addPropertySource));
        }
    }
    return new EncryptableEnumerablePropertySourceWrapper<>(compositePropertySource, resolver, propertyFilter);
}
 
Example #7
Source File: ConfigurationChangeDetector.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of MapPropertySource that correspond to the current state of the
 * system. This only handles the PropertySource objects that are returned.
 * @param propertySourceLocator Spring's property source locator
 * @param environment Spring environment
 * @return a list of MapPropertySource that correspond to the current state of the
 * system
 */
protected List<MapPropertySource> locateMapPropertySources(
		PropertySourceLocator propertySourceLocator, Environment environment) {

	List<MapPropertySource> result = new ArrayList<>();
	PropertySource propertySource = propertySourceLocator.locate(environment);
	if (propertySource instanceof MapPropertySource) {
		result.add((MapPropertySource) propertySource);
	}
	else if (propertySource instanceof CompositePropertySource) {
		result.addAll(((CompositePropertySource) propertySource).getPropertySources()
				.stream().filter(p -> p instanceof MapPropertySource)
				.map(p -> (MapPropertySource) p).collect(Collectors.toList()));
	}
	else {
		this.log.debug("Found property source that cannot be handled: "
				+ propertySource.getClass());
	}

	return result;
}
 
Example #8
Source File: ConfigMapPropertySourceLocator.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public PropertySource locate(Environment environment) {
	if (environment instanceof ConfigurableEnvironment) {
		ConfigurableEnvironment env = (ConfigurableEnvironment) environment;

		List<ConfigMapConfigProperties.NormalizedSource> sources = this.properties
				.determineSources();
		CompositePropertySource composite = new CompositePropertySource(
				"composite-configmap");
		if (this.properties.isEnableApi()) {
			sources.forEach(s -> composite.addFirstPropertySource(
					getMapPropertySourceForSingleConfigMap(env, s)));
		}

		addPropertySourcesFromPaths(environment, composite);

		return composite;
	}
	return null;
}
 
Example #9
Source File: LeasingVaultPropertySourceLocatorUnitTests.java    From spring-cloud-vault with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLocateLeaseAwareSources() {

	RequestedSecret rotating = RequestedSecret.rotating("secret/rotating");
	DefaultSecretBackendConfigurer configurer = new DefaultSecretBackendConfigurer();
	configurer.add(rotating);
	configurer.add("database/mysql/creds/readonly");

	this.propertySourceLocator = new LeasingVaultPropertySourceLocator(
			new VaultProperties(), configurer, this.secretLeaseContainer);

	PropertySource<?> propertySource = this.propertySourceLocator
			.locate(this.configurableEnvironment);

	assertThat(propertySource).isInstanceOf(CompositePropertySource.class);

	verify(this.secretLeaseContainer).addRequestedSecret(rotating);
	verify(this.secretLeaseContainer).addRequestedSecret(
			RequestedSecret.renewable("database/mysql/creds/readonly"));
}
 
Example #10
Source File: ApolloApplicationContextInitializer.java    From apollo with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize Apollo Configurations Just after environment is ready.
 *
 * @param environment
 */
protected void initialize(ConfigurableEnvironment environment) {

  if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
    //already initialized
    return;
  }

  String namespaces = environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, ConfigConsts.NAMESPACE_APPLICATION);
  logger.debug("Apollo bootstrap namespaces: {}", namespaces);
  List<String> namespaceList = NAMESPACE_SPLITTER.splitToList(namespaces);

  CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME);
  for (String namespace : namespaceList) {
    Config config = ConfigService.getConfig(namespace);

    composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
  }

  environment.getPropertySources().addFirst(composite);
}
 
Example #11
Source File: SecretsPropertySourceLocator.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public PropertySource locate(Environment environment) {
	if (environment instanceof ConfigurableEnvironment) {
		ConfigurableEnvironment env = (ConfigurableEnvironment) environment;

		List<SecretsConfigProperties.NormalizedSource> sources = this.properties
				.determineSources();
		CompositePropertySource composite = new CompositePropertySource(
				"composite-secrets");
		if (this.properties.isEnableApi()) {
			sources.forEach(s -> composite.addFirstPropertySource(
					getKubernetesPropertySourceForSingleSecret(env, s)));
		}

		// read for secrets mount
		putPathConfig(composite);

		return composite;
	}
	return null;
}
 
Example #12
Source File: ConfigurationSpringInitializer.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
/**
 * Get property names from {@link EnumerablePropertySource}, and get property value from {@link ConfigurableEnvironment#getProperty(String)}
 */
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()) {
      try {
        configFromSpringBoot.put(propertyName, environment.getProperty(propertyName, Object.class));
      } catch (Exception e) {
        throw new RuntimeException(
            "set up spring property source failed.If you still want to start up the application and ignore errors, you can set servicecomb.config.ignoreResolveFailure to true.",
            e);
      }
    }
    return;
  }

  LOGGER.debug("a none EnumerablePropertySource is ignored, propertySourceName = [{}]", propertySource.getName());
}
 
Example #13
Source File: SpringApplication.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
/**
 * Add, remove or re-order any {@link PropertySource}s in this application's
 * environment.
 * @param environment this application's environment
 * @param args arguments passed to the {@code run} method
 * @see #configureEnvironment(ConfigurableEnvironment, String[])
 */
protected void configurePropertySources(ConfigurableEnvironment environment,
		String[] args) {
	MutablePropertySources sources = environment.getPropertySources();
	if (this.defaultProperties != null && !this.defaultProperties.isEmpty()) {
		sources.addLast(
				new MapPropertySource("defaultProperties", this.defaultProperties));
	}
	if (this.addCommandLineProperties && args.length > 0) {
		String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
		if (sources.contains(name)) {
			PropertySource<?> source = sources.get(name);
			CompositePropertySource composite = new CompositePropertySource(name);
			composite.addPropertySource(new SimpleCommandLinePropertySource(
					"springApplicationCommandLineArgs", args));
			composite.addPropertySource(source);
			sources.replace(name, composite);
		}
		else {
			sources.addFirst(new SimpleCommandLinePropertySource(args));
		}
	}
}
 
Example #14
Source File: ConfigurationChangeDetector.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
/**
 * Finds all registered property sources of the given type.
 */
protected <S extends PropertySource<?>> List<S> findPropertySources(Class<S> sourceClass) {
    List<S> managedSources = new LinkedList<>();

    LinkedList<PropertySource<?>> sources = toLinkedList(environment.getPropertySources());
    while (!sources.isEmpty()) {
        PropertySource<?> source = sources.pop();
        if (source instanceof CompositePropertySource) {
            CompositePropertySource comp = (CompositePropertySource) source;
            sources.addAll(comp.getPropertySources());
        } else if (sourceClass.isInstance(source)) {
            managedSources.add(sourceClass.cast(source));
        }
    }

    return managedSources;
}
 
Example #15
Source File: BootstrapConfigurationTests.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Override
public PropertySource<?> locate(Environment environment) {
	if (this.name != null) {
		then(this.name)
				.isEqualTo(environment.getProperty("spring.application.name"));
	}
	if (this.fail) {
		throw new RuntimeException("Planned");
	}
	CompositePropertySource compositePropertySource = new CompositePropertySource(
			"listTestBootstrap");
	compositePropertySource.addFirstPropertySource(
			new MapPropertySource("testBootstrap1", MAP1));
	compositePropertySource.addFirstPropertySource(
			new MapPropertySource("testBootstrap2", MAP2));
	return compositePropertySource;
}
 
Example #16
Source File: DSSSpringApplication.java    From DataSphereStudio with Apache License 2.0 6 votes vote down vote up
private static void addOrUpdateRemoteConfig(Environment env, boolean isUpdateOrNot) {
    StandardEnvironment environment = (StandardEnvironment) env;
    PropertySource propertySource = environment.getPropertySources().get("bootstrapProperties");
    if(propertySource == null) {
        return;
    }
    CompositePropertySource source = (CompositePropertySource) propertySource;
    for (String key: source.getPropertyNames()) {
        Object val = source.getProperty(key);
        if(val == null) {
            continue;
        }
        if(isUpdateOrNot) {
            logger.info("update remote config => " + key + " = " + source.getProperty(key));
            BDPConfiguration.set(key, val.toString());
        } else {
            logger.info("add remote config => " + key + " = " + source.getProperty(key));
            BDPConfiguration.setIfNotExists(key, val.toString());
        }
    }
}
 
Example #17
Source File: MultiModuleConfigServicePropertySourceLocator.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
private void loadDepEnvironments(org.springframework.core.env.Environment environment, CompositePropertySource composite, String state) {
    depApplications.forEach(dep -> {
        ConfigClientProperties properties = this.defaultProperties.override(environment);
        properties.setName(dep.getApplicationName());
        RestTemplate restTemplate = this.restTemplate == null ? getSecureRestTemplate(properties) : this.restTemplate;
        Environment result = getRemoteEnvironment(restTemplate, properties, "master", state);
        if (result != null) {
            logger.info(String.format("Located environment: name=%s, profiles=%s, label=%s, version=%s, state=%s",
                    result.getName(),
                    result.getProfiles() == null ? "" : Arrays.asList(result.getProfiles()),
                    result.getLabel(), result.getVersion(), result.getState()));

            processApplicationResult(composite, result);
        }
    });
}
 
Example #18
Source File: EnvironmentDecryptApplicationInitializerTests.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecryptCompositePropertySource() {
	ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext();
	EnvironmentDecryptApplicationInitializer initializer = new EnvironmentDecryptApplicationInitializer(
			Encryptors.noOpText());

	MapPropertySource devProfile = new MapPropertySource("dev-profile",
			Collections.singletonMap("key", "{cipher}value1"));

	MapPropertySource defaultProfile = new MapPropertySource("default-profile",
			Collections.singletonMap("key", "{cipher}value2"));

	CompositePropertySource cps = mock(CompositePropertySource.class);
	when(cps.getPropertyNames()).thenReturn(devProfile.getPropertyNames());
	when(cps.getPropertySources())
			.thenReturn(Arrays.asList(devProfile, defaultProfile));
	ctx.getEnvironment().getPropertySources().addLast(cps);

	initializer.initialize(ctx);
	then(ctx.getEnvironment().getProperty("key")).isEqualTo("value1");
}
 
Example #19
Source File: Deployer.java    From spring-cloud-cli with Apache License 2.0 6 votes vote down vote up
private PropertySource<?> loadPropertySource(Resource resource, String path) {
	if (resource.exists()) {
		try {
			List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(path,
					resource);
			if (sources != null) {
				logger.info("Loaded YAML properties from: " + resource);
			} else if (sources == null || sources.isEmpty()){
			    return null;
               }

			CompositePropertySource composite = new CompositePropertySource("cli-sources");

			for (PropertySource propertySource : sources) {
				composite.addPropertySource(propertySource);
			}

			return composite;
		}
		catch (IOException e) {
		}
	}
	return null;
}
 
Example #20
Source File: EurekaClientConfigBeanTests.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
@Test
public void serviceUrlWithCompositePropertySource() {
	CompositePropertySource source = new CompositePropertySource("composite");
	this.context.getEnvironment().getPropertySources().addFirst(source);
	source.addPropertySource(new MapPropertySource("config",
			Collections.<String, Object>singletonMap(
					"eureka.client.serviceUrl.defaultZone",
					"https://example.com,https://example2.com, https://www.hugedomains.com/domain_profile.cfm?d=example3&e=com")));
	this.context.register(PropertyPlaceholderAutoConfiguration.class,
			TestConfiguration.class);
	this.context.refresh();
	assertThat(this.context.getBean(EurekaClientConfigBean.class).getServiceUrl()
			.toString()).isEqualTo(
					"{defaultZone=https://example.com,https://example2.com, https://www.hugedomains.com/domain_profile.cfm?d=example3&e=com}");
	assertThat(getEurekaServiceUrlsForDefaultZone()).isEqualTo(
			"[https://example.com/, https://example2.com/, https://www.hugedomains.com/domain_profile.cfm?d=example3&e=com/]");
}
 
Example #21
Source File: ConfigServerHealthIndicator.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Override
protected void doHealthCheck(Builder builder) throws Exception {
	PropertySource<?> propertySource = getPropertySource();
	builder.up();
	if (propertySource instanceof CompositePropertySource) {
		List<String> sources = new ArrayList<>();
		for (PropertySource<?> ps : ((CompositePropertySource) propertySource)
				.getPropertySources()) {
			sources.add(ps.getName());
		}
		builder.withDetail("propertySources", sources);
	}
	else if (propertySource != null) {
		builder.withDetail("propertySources", propertySource.toString());
	}
	else {
		builder.unknown().withDetail("error", "no property sources located");
	}
}
 
Example #22
Source File: PropertySourceBootstrapConfiguration.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private Set<String> addIncludedProfilesTo(Set<String> profiles,
		PropertySource<?> propertySource) {
	if (propertySource instanceof CompositePropertySource) {
		for (PropertySource<?> nestedPropertySource : ((CompositePropertySource) propertySource)
				.getPropertySources()) {
			addIncludedProfilesTo(profiles, nestedPropertySource);
		}
	}
	else {
		Collections.addAll(profiles, getProfilesForValue(propertySource.getProperty(
				ConfigFileApplicationListener.INCLUDE_PROFILES_PROPERTY)));
	}
	return profiles;
}
 
Example #23
Source File: LeasingVaultPropertySourceLocatorUnitTests.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLocatePropertySources() {

	PropertySource<?> propertySource = this.propertySourceLocator
			.locate(this.configurableEnvironment);

	assertThat(propertySource).isInstanceOf(CompositePropertySource.class);

	CompositePropertySource composite = (CompositePropertySource) propertySource;
	assertThat(composite.getPropertySources()).hasSize(1);
	verify(this.secretLeaseContainer)
			.addRequestedSecret(RequestedSecret.rotating("secret/application"));
}
 
Example #24
Source File: VaultPropertySourceLocatorSupport.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link CompositePropertySource}.
 * @param environment must not be {@literal null}.
 * @return the composite {@link PropertySource}.
 */
protected CompositePropertySource createCompositePropertySource(
		Environment environment) {

	List<PropertySource<?>> propertySources = doCreatePropertySources(environment);

	return doCreateCompositePropertySource(this.propertySourceName, propertySources);
}
 
Example #25
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 #26
Source File: VaultPropertySourceLocatorSupport.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link CompositePropertySource} given a {@link List} of
 * {@link PropertySource}s.
 * @param propertySourceName the property source name.
 * @param propertySources the property sources.
 * @return the {@link CompositePropertySource} to use.
 */
protected CompositePropertySource doCreateCompositePropertySource(
		String propertySourceName, List<PropertySource<?>> propertySources) {

	CompositePropertySource compositePropertySource = new CompositePropertySource(
			propertySourceName);

	for (PropertySource<?> propertySource : propertySources) {
		compositePropertySource.addPropertySource(propertySource);
	}

	return compositePropertySource;
}
 
Example #27
Source File: DruidConfiguration.java    From wenku with MIT License 5 votes vote down vote up
private void getPropertiesFromSource(PropertySource<?> propertySource, Map<String, Object> map) {
    if (propertySource instanceof MapPropertySource) {
        for (String key : ((MapPropertySource) propertySource).getPropertyNames()) {
            if (key.startsWith(DB_PREFIX)) {
                map.put(key.replaceFirst(DB_PREFIX, ""), propertySource.getProperty(key));
            }
        }
    }

    if (propertySource instanceof CompositePropertySource) {
        for (PropertySource<?> s : ((CompositePropertySource) propertySource).getPropertySources()) {
            getPropertiesFromSource(s, map);
        }
    }
}
 
Example #28
Source File: VaultPropertySourceLocatorSupport.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
@Override
public PropertySource<?> locate(Environment environment) {

	if (this.propertySourceLocatorConfiguration instanceof EnvironmentAware) {
		((EnvironmentAware) this.propertySourceLocatorConfiguration)
				.setEnvironment(environment);
	}

	CompositePropertySource propertySource = createCompositePropertySource(
			environment);
	initialize(propertySource);

	return propertySource;
}
 
Example #29
Source File: VaultPropertySourceLocator.java    From spring-cloud-vault with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize nested {@link PropertySource}s inside the
 * {@link CompositePropertySource}.
 * @param propertySource the {@link CompositePropertySource} to initialize.
 */
protected void initialize(CompositePropertySource propertySource) {

	for (PropertySource<?> source : propertySource.getPropertySources()) {
		((VaultPropertySource) source).init();
	}
}
 
Example #30
Source File: ConfigurationClassParser.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void addPropertySource(PropertySource<?> propertySource) {
	String name = propertySource.getName();
	MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();

	if (this.propertySourceNames.contains(name)) {
		// We've already added a version, we need to extend it
		PropertySource<?> existing = propertySources.get(name);
		if (existing != null) {
			PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
					((ResourcePropertySource) propertySource).withResourceName() : propertySource);
			if (existing instanceof CompositePropertySource) {
				((CompositePropertySource) existing).addFirstPropertySource(newSource);
			}
			else {
				if (existing instanceof ResourcePropertySource) {
					existing = ((ResourcePropertySource) existing).withResourceName();
				}
				CompositePropertySource composite = new CompositePropertySource(name);
				composite.addPropertySource(newSource);
				composite.addPropertySource(existing);
				propertySources.replace(name, composite);
			}
			return;
		}
	}

	if (this.propertySourceNames.isEmpty()) {
		propertySources.addLast(propertySource);
	}
	else {
		String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
		propertySources.addBefore(firstProcessed, propertySource);
	}
	this.propertySourceNames.add(name);
}