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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #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: 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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #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: ServiceCombPropertySourceLocator.java    From spring-cloud-huawei with Apache License 2.0 5 votes vote down vote up
@Override
public PropertySource<?> locate(Environment environment) {
  ServiceCombConfigPropertySource serviceCombConfigPropertySource = new ServiceCombConfigPropertySource(
      ConfigConstants.PROPERTYSOURCE_NAME,
      serviceCombConfigClient);
  try {
    serviceCombConfigPropertySource
        .loadAllRemoteConfig(serviceCombConfigProperties, project);
  } catch (RemoteOperationException e) {
    LOGGER.error(e.getMessage(), e);
  }
  CompositePropertySource composite = new CompositePropertySource(ConfigConstants.PROPERTYSOURCE_NAME);
  composite.addPropertySource(serviceCombConfigPropertySource);
  return composite;
}
 
Example #23
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);
}
 
Example #24
Source File: MqEnvProp.java    From pmq with Apache License 2.0 5 votes vote down vote up
private void extract(String root, Map<String, PropertySource<?>> map,
		PropertySource<?> source) {
	if (source instanceof CompositePropertySource) {
		for (PropertySource<?> nest : ((CompositePropertySource) source)
				.getPropertySources()) {
			extract(source.getName() + ":", map, nest);
		}
	}
	else {
		map.put(root + source.getName(), source);
	}
}
 
Example #25
Source File: ConsulPropertySourceLocatorFilesTests.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Test
public void propertySourcesFound() throws Exception {
    String foo = this.environment.getProperty("foo");
    assertThat(foo).as("foo was wrong").isEqualTo("bar-app-dev");

    String myBaz = this.environment.getProperty("my.baz");
    assertThat(myBaz).as("my.baz was wrong").isEqualTo("bar-app-dev");

    MutablePropertySources propertySources = this.environment.getPropertySources();
    PropertySource<?> bootstrapProperties = propertySources
            .get("bootstrapProperties");
    assertThat(bootstrapProperties).as("bootstrapProperties was null").isNotNull();
    assertThat(bootstrapProperties).as("bootstrapProperties was wrong type")
            .isInstanceOf(CompositePropertySource.class);

    Collection<PropertySource<?>> consulSources = ((CompositePropertySource) bootstrapProperties)
            .getPropertySources();
    assertThat(consulSources).as("consulSources was wrong size").hasSize(1);

    PropertySource<?> consulSource = consulSources.iterator().next();
    assertThat(consulSource).as("consulSource was wrong type")
            .isInstanceOf(CompositePropertySource.class);
    Collection<PropertySource<?>> fileSources = ((CompositePropertySource) consulSource)
            .getPropertySources();
    assertThat(fileSources).as("fileSources was wrong size").hasSize(4);

    assertFileSourceNames(fileSources, APP_NAME_DEV_PROPS, APP_NAME_PROPS,
            APPLICATION_DEV_YML, APPLICATION_YML);
}
 
Example #26
Source File: MultiModuleConfigServicePropertySourceLocator.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private void processApplicationResult(CompositePropertySource composite, Environment result) {
    if (result.getPropertySources() != null) { // result.getPropertySources() can be null if using xml
        for (PropertySource source : result.getPropertySources()) {
            @SuppressWarnings("unchecked")
            Map<String, Object> map = (Map<String, Object>) source
                    .getSource();
            composite.addPropertySource(new MapPropertySource(source
                    .getName(), map));
        }
    }
}
 
Example #27
Source File: MultiModuleConfigServicePropertySourceLocator.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private void addConfigLocationFiles(ConfigurableEnvironment environment, CompositePropertySource composite) {
    MutablePropertySources ps = environment.getPropertySources();
    for (org.springframework.core.env.PropertySource<?> propertySource : ps) {
        if (propertySource.getName().startsWith("applicationConfig: [file:")) {
            logger.info("Adding {} to Cloud Config Client PropertySource", propertySource.getName());
            composite.addPropertySource(propertySource);
        }
    }
}
 
Example #28
Source File: ConfigurationClassParser.java    From java-technology-stack 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);
}
 
Example #29
Source File: EnvProp.java    From radar with Apache License 2.0 5 votes vote down vote up
private void extract(String root, Map<String, PropertySource<?>> map,
		PropertySource<?> source) {
	if (source instanceof CompositePropertySource) {
		for (PropertySource<?> nest : ((CompositePropertySource) source)
				.getPropertySources()) {
			extract(source.getName() + ":", map, nest);
		}
	}
	else {
		map.put(root + source.getName(), source);
	}
}
 
Example #30
Source File: EnvironmentUtils.java    From dubbo-spring-boot-project with Apache License 2.0 5 votes vote down vote up
private static void extract(String root, Map<String, PropertySource<?>> map,
                            PropertySource<?> source) {
    if (source instanceof CompositePropertySource) {
        for (PropertySource<?> nest : ((CompositePropertySource) source)
                .getPropertySources()) {
            extract(source.getName() + ":", map, nest);
        }
    } else {
        map.put(root + source.getName(), source);
    }
}