Java Code Examples for org.springframework.cloud.config.environment.Environment#getPropertySources()

The following examples show how to use org.springframework.cloud.config.environment.Environment#getPropertySources() . 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: SentinelRuleLocator.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void log(Environment result) {

        RecordLog.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()));

        List<PropertySource> propertySourceList = result.getPropertySources();
        if (propertySourceList != null) {
            int propertyCount = 0;
            for (PropertySource propertySource : propertySourceList) {
                propertyCount += propertySource.getSource().size();
            }
            RecordLog.info("[SentinelRuleLocator] Environment {} has {} property sources with {} properties",
                result.getName(), result.getPropertySources().size(), propertyCount);
        }
    }
 
Example 2
Source File: ConfigServicePropertySourceLocator.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
private void log(Environment result) {
	if (logger.isInfoEnabled()) {
		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()));
	}
	if (logger.isDebugEnabled()) {
		List<PropertySource> propertySourceList = result.getPropertySources();
		if (propertySourceList != null) {
			int propertyCount = 0;
			for (PropertySource propertySource : propertySourceList) {
				propertyCount += propertySource.getSource().size();
			}
			logger.debug(String.format(
					"Environment %s has %d property sources with %d properties.",
					result.getName(), result.getPropertySources().size(),
					propertyCount));
		}

	}
}
 
Example 3
Source File: PassthruEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void originTrackedPropertySourceWithoutOriginWorks() {
	MockEnvironment mockEnvironment = new MockEnvironment();
	mockEnvironment.setProperty("normalKey", "normalValue");
	mockEnvironment.getPropertySources()
			.addFirst(new OriginTrackedMapPropertySource("myorigintrackedsource",
					Collections.singletonMap("keyNoOrigin", "valueNoOrigin")));
	PassthruEnvironmentRepository repository = new PassthruEnvironmentRepository(
			mockEnvironment);
	Environment environment = repository.findOne("testapp", "default", "master",
			true);
	assertThat(environment).isNotNull();
	List<PropertySource> propertySources = environment.getPropertySources();
	assertThat(propertySources).hasSize(2);
	for (PropertySource propertySource : propertySources) {
		Map source = propertySource.getSource();
		if (propertySource.getName().equals("myorigintrackedsource")) {
			assertThat(source).containsEntry("keyNoOrigin", "valueNoOrigin");
		}
		else if (propertySource.getName().equals("mockProperties")) {
			assertThat(source).containsEntry("normalKey", "normalValue");
		}
	}
}
 
Example 4
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 5
Source File: EnvironmentCleaner.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
public Environment clean(Environment value, String workingDir, String uri) {
	Environment result = new Environment(value);
	for (PropertySource source : value.getPropertySources()) {
		String name = source.getName().replace(workingDir, "");
		name = name.replace("applicationConfig: [", "");
		name = uri + "/" + name.replace("]", "");
		result.add(new PropertySource(name, clean(source.getSource(), uri)));
	}
	return result;
}
 
Example 6
Source File: CipherEnvironmentEncryptor.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
private Environment decrypt(Environment environment, TextEncryptorLocator encryptor) {
	Environment result = new Environment(environment);
	for (PropertySource source : environment.getPropertySources()) {
		Map<Object, Object> map = new LinkedHashMap<Object, Object>(
				source.getSource());
		for (Map.Entry<Object, Object> entry : new LinkedHashSet<>(map.entrySet())) {
			Object key = entry.getKey();
			String name = key.toString();
			if (entry.getValue() != null
					&& entry.getValue().toString().startsWith("{cipher}")) {
				String value = entry.getValue().toString();
				map.remove(key);
				try {
					value = value.substring("{cipher}".length());
					value = encryptor
							.locate(this.helper.getEncryptorKeys(name,
									StringUtils.arrayToCommaDelimitedString(
											environment.getProfiles()),
									value))
							.decrypt(this.helper.stripPrefix(value));
				}
				catch (Exception e) {
					value = "<n/a>";
					name = "invalid." + name;
					String message = "Cannot decrypt key: " + key + " ("
							+ e.getClass() + ": " + e.getMessage() + ")";
					if (logger.isDebugEnabled()) {
						logger.debug(message, e);
					}
					else if (logger.isWarnEnabled()) {
						logger.warn(message);
					}
				}
				map.put(name, value);
			}
		}
		result.add(new PropertySource(source.getName(), map));
	}
	return result;
}
 
Example 7
Source File: AwsS3EnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
private void assertExpectedEnvironment(Environment env, String applicationName,
		String label, String version, int propertySourceCount, String... profiles) {
	assertThat(env.getName()).isEqualTo(applicationName);
	assertThat(env.getProfiles()).isEqualTo(profiles);
	assertThat(env.getLabel()).isEqualTo(label);
	assertThat(env.getVersion()).isEqualTo(version);
	assertThat(env.getPropertySources().size()).isEqualTo(propertySourceCount);
	for (PropertySource ps : env.getPropertySources()) {
		assertThat(ps.getSource()).isEqualTo(expectedProperties);
	}
}
 
Example 8
Source File: CustomCompositeEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	Environment environment = new TestRestTemplate().getForObject(
			"http://localhost:" + this.port + "/foo/development/",
			Environment.class);
	List<PropertySource> propertySources = environment.getPropertySources();
	assertThat(3).isEqualTo(propertySources.size());
	assertThat("overrides").isEqualTo(propertySources.get(0).getName());
	assertThat(propertySources.get(1).getName().contains("config-repo")).isTrue();
	assertThat("p").isEqualTo(propertySources.get(2).getName());
}
 
Example 9
Source File: CustomCompositeEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void contextLoads() {
	Environment environment = new TestRestTemplate().getForObject(
			"http://localhost:" + this.port + "/foo/development/",
			Environment.class);
	List<PropertySource> propertySources = environment.getPropertySources();
	assertThat(3).isEqualTo(propertySources.size());
	assertThat("overrides").isEqualTo(propertySources.get(0).getName());
	assertThat(propertySources.get(1).getName().contains("config-repo")).isTrue();
	assertThat("p").isEqualTo(propertySources.get(2).getName());
}
 
Example 10
Source File: ConfigServerTestUtils.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
public static Object getProperty(Environment env, String sourceNameEndsWith,
		String property) {
	for (PropertySource source : env.getPropertySources()) {
		if (source.getName().endsWith(sourceNameEndsWith)) {
			return source.getSource().get(property);
		}
	}
	return null;
}
 
Example 11
Source File: NativeEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
protected Environment clean(Environment value) {
	Environment result = new Environment(value.getName(), value.getProfiles(),
			value.getLabel(), this.version, value.getState());
	for (PropertySource source : value.getPropertySources()) {
		String name = source.getName();
		if (this.environment.getPropertySources().contains(name)) {
			continue;
		}
		name = name.replace("applicationConfig: [", "");
		name = name.replace("]", "");
		if (this.searchLocations != null) {
			boolean matches = false;
			String normal = name;
			if (normal.startsWith("file:")) {
				normal = StringUtils
						.cleanPath(new File(normal.substring("file:".length()))
								.getAbsolutePath());
			}
			String profile = result.getProfiles() == null ? null
					: StringUtils.arrayToCommaDelimitedString(result.getProfiles());
			for (String pattern : getLocations(result.getName(), profile,
					result.getLabel()).getLocations()) {
				if (!pattern.contains(":")) {
					pattern = "file:" + pattern;
				}
				if (pattern.startsWith("file:")) {
					pattern = StringUtils
							.cleanPath(new File(pattern.substring("file:".length()))
									.getAbsolutePath())
							+ "/";
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Testing pattern: " + pattern
							+ " with property source: " + name);
				}
				if (normal.startsWith(pattern)
						&& !normal.substring(pattern.length()).contains("/")) {
					matches = true;
					break;
				}
			}
			if (!matches) {
				// Don't include this one: it wasn't matched by our search locations
				if (logger.isDebugEnabled()) {
					logger.debug("Not adding property source: " + name);
				}
				continue;
			}
		}
		logger.info("Adding property source: " + name);
		result.add(new PropertySource(name, source.getSource()));
	}
	return result;
}
 
Example 12
Source File: EnvironmentController.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
private Map<String, Object> convertToProperties(Environment profiles) {

		// Map of unique keys containing full map of properties for each unique
		// key
		Map<String, Map<String, Object>> map = new LinkedHashMap<>();
		List<PropertySource> sources = new ArrayList<>(profiles.getPropertySources());
		Collections.reverse(sources);
		Map<String, Object> combinedMap = new LinkedHashMap<>();
		for (PropertySource source : sources) {

			@SuppressWarnings("unchecked")
			Map<String, Object> value = (Map<String, Object>) source.getSource();
			for (String key : value.keySet()) {

				if (!key.contains("[")) {

					// Not an array, add unique key to the map
					combinedMap.put(key, value.get(key));

				}
				else {

					// An existing array might have already been added to the property map
					// of an unequal size to the current array. Replace the array key in
					// the current map.
					key = key.substring(0, key.indexOf("["));
					Map<String, Object> filtered = new LinkedHashMap<>();
					for (String index : value.keySet()) {
						if (index.startsWith(key + "[")) {
							filtered.put(index, value.get(index));
						}
					}
					map.put(key, filtered);
				}
			}

		}

		// Combine all unique keys for array values into the combined map
		for (Entry<String, Map<String, Object>> entry : map.entrySet()) {
			combinedMap.putAll(entry.getValue());
		}

		postProcessProperties(combinedMap);
		return combinedMap;
	}
 
Example 13
Source File: ConfigServerHealthIndicator.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	builder.up();
	List<Map<String, Object>> details = new ArrayList<>();
	for (String name : this.repositories.keySet()) {
		Repository repository = this.repositories.get(name);
		String application = (repository.getName() == null) ? name
				: repository.getName();
		String profiles = repository.getProfiles();

		try {
			Environment environment = this.environmentRepository.findOne(application,
					profiles, repository.getLabel(), false);

			HashMap<String, Object> detail = new HashMap<>();
			detail.put("name", environment.getName());
			detail.put("label", environment.getLabel());
			if (environment.getProfiles() != null
					&& environment.getProfiles().length > 0) {
				detail.put("profiles", Arrays.asList(environment.getProfiles()));
			}

			if (!CollectionUtils.isEmpty(environment.getPropertySources())) {
				List<String> sources = new ArrayList<>();
				for (PropertySource source : environment.getPropertySources()) {
					sources.add(source.getName());
				}
				detail.put("sources", sources);
			}
			details.add(detail);
		}
		catch (Exception e) {
			logger.debug("Could not read repository: " + application, e);
			HashMap<String, String> map = new HashMap<>();
			map.put("application", application);
			map.put("profiles", profiles);
			builder.withDetail("repository", map);
			builder.down(e);
			return;
		}
	}
	builder.withDetail("repositories", details);

}
 
Example 14
Source File: CompositeEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 4 votes vote down vote up
@Test
public void testOrder() {
	PropertySource p1 = mock(PropertySource.class);
	doReturn("p1").when(p1).getName();
	PropertySource p2 = mock(PropertySource.class);
	doReturn("p2").when(p2).getName();
	PropertySource p3 = mock(PropertySource.class);
	doReturn("p3").when(p3).getName();
	PropertySource p4 = mock(PropertySource.class);
	doReturn("p4").when(p4).getName();
	PropertySource p5 = mock(PropertySource.class);
	doReturn("p5").when(p5).getName();
	String sLoc1 = "loc1";
	String sLoc2 = "loc2";
	String sLoc3 = "loc3";
	String sLoc4 = "loc4";
	String sLoc5 = "loc5";
	Environment e1 = new Environment("app", "dev");
	e1.add(p1);
	e1.add(p5);
	Environment e2 = new Environment("app", "dev");
	e2.add(p2);
	Environment e3 = new Environment("app", "dev");
	e3.add(p3);
	e3.add(p4);
	SearchPathLocator.Locations loc1 = new SearchPathLocator.Locations("app", "dev",
			"label", "version", new String[] { sLoc1 });
	SearchPathLocator.Locations loc2 = new SearchPathLocator.Locations("app", "dev",
			"label", "version", new String[] { sLoc5, sLoc4 });
	SearchPathLocator.Locations loc3 = new SearchPathLocator.Locations("app", "dev",
			"label", "version", new String[] { sLoc3, sLoc2 });
	List<EnvironmentRepository> repos = new ArrayList<EnvironmentRepository>();
	repos.add(new TestOrderedEnvironmentRepository(3, e1, loc1));
	repos.add(new TestOrderedEnvironmentRepository(2, e3, loc2));
	repos.add(new TestOrderedEnvironmentRepository(1, e2, loc3));
	SearchPathCompositeEnvironmentRepository compositeRepo = new SearchPathCompositeEnvironmentRepository(
			repos);
	Environment compositeEnv = compositeRepo.findOne("foo", "bar", "world", false);
	List<PropertySource> propertySources = compositeEnv.getPropertySources();
	assertThat(propertySources.size()).isEqualTo(5);
	assertThat(propertySources.get(0).getName()).isEqualTo("p2");
	assertThat(propertySources.get(1).getName()).isEqualTo("p3");
	assertThat(propertySources.get(2).getName()).isEqualTo("p4");
	assertThat(propertySources.get(3).getName()).isEqualTo("p1");
	assertThat(propertySources.get(4).getName()).isEqualTo("p5");

	SearchPathLocator.Locations locations = compositeRepo.getLocations("app", "dev",
			"label");
	String[] locationStrings = locations.getLocations();
	assertThat(locationStrings.length).isEqualTo(5);
	assertThat(locationStrings[0]).isEqualTo(sLoc3);
	assertThat(locationStrings[1]).isEqualTo(sLoc2);
	assertThat(locationStrings[2]).isEqualTo(sLoc5);
	assertThat(locationStrings[3]).isEqualTo(sLoc4);
	assertThat(locationStrings[4]).isEqualTo(sLoc1);
}