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

The following examples show how to use org.springframework.cloud.config.environment.Environment#add() . 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: CipherEnvironmentEncryptorTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecryptEnvironmentIncludeOrigin() {
	// given
	String secret = randomUUID().toString();

	// when
	Environment environment = new Environment("name", "profile", "label");
	String encrypted = "{cipher}" + this.textEncryptor.encrypt(secret);
	environment.add(new PropertySource("a",
			Collections.<Object, Object>singletonMap(environment.getName(),
					new PropertyValueDescriptor(encrypted, "encrypted value"))));

	// then
	assertThat(this.encryptor.decrypt(environment).getPropertySources().get(0)
			.getSource().get(environment.getName())).isEqualTo(secret);
}
 
Example 2
Source File: PassthruEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Override
public Environment findOne(String application, String profile, String label,
		boolean includeOrigin) {
	Environment result = new Environment(application,
			StringUtils.commaDelimitedListToStringArray(profile), label, null, null);
	for (org.springframework.core.env.PropertySource<?> source : this.environment
			.getPropertySources()) {
		String name = source.getName();
		if (!this.standardSources.contains(name)
				&& source instanceof MapPropertySource) {
			result.add(new PropertySource(name, getMap(source, includeOrigin)));
		}
	}
	return result;

}
 
Example 3
Source File: CredhubEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
private void addDefaultPropertySource(Environment environment, String application,
		String profile, String label) {
	Map<Object, Object> properties = findProperties(application, profile, label);
	if (!properties.isEmpty()) {
		PropertySource propertySource = new PropertySource(
				"credhub-" + application + "-" + profile + "-" + label, properties);
		environment.add(propertySource);
	}
}
 
Example 4
Source File: CipherEnvironmentEncryptorTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBeAbleToUseNullAsPropertyValue() {

	// when
	Environment environment = new Environment("name", "profile", "label");
	environment.add(new PropertySource("a",
			Collections.<Object, Object>singletonMap(environment.getName(), null)));

	// then
	assertThat(this.encryptor.decrypt(environment).getPropertySources().get(0)
			.getSource().get(environment.getName())).isEqualTo(null);
}
 
Example 5
Source File: CipherEnvironmentEncryptorTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecryptEnvironmentWithKey() {
	// given
	String secret = randomUUID().toString();

	// when
	Environment environment = new Environment("name", "profile", "label");
	environment.add(new PropertySource("a",
			Collections.<Object, Object>singletonMap(environment.getName(),
					"{cipher}{key:test}" + this.textEncryptor.encrypt(secret))));

	// then
	assertThat(this.encryptor.decrypt(environment).getPropertySources().get(0)
			.getSource().get(environment.getName())).isEqualTo(secret);
}
 
Example 6
Source File: CipherEnvironmentEncryptorTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecryptEnvironment() {
	// given
	String secret = randomUUID().toString();

	// when
	Environment environment = new Environment("name", "profile", "label");
	environment.add(new PropertySource("a", Collections.<Object, Object>singletonMap(
			environment.getName(), "{cipher}" + this.textEncryptor.encrypt(secret))));

	// then
	assertThat(this.encryptor.decrypt(environment).getPropertySources().get(0)
			.getSource().get(environment.getName())).isEqualTo(secret);
}
 
Example 7
Source File: EnvironmentControllerIntegrationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void environmentWithApplicationContainingSlash() throws Exception {
	Environment environment = new Environment("foo/app", "default");
	environment.add(new PropertySource("foo", new HashMap<>()));
	when(this.repository.findOne("foo/app", "default", null, false))
			.thenReturn(environment);
	this.mvc.perform(MockMvcRequestBuilders.get("/foo(_)app/default"))
			.andExpect(MockMvcResultMatchers.status().isOk())
			.andExpect(MockMvcResultMatchers.content()
					.string(Matchers.containsString("\"propertySources\":")));
}
 
Example 8
Source File: EnvironmentControllerIntegrationTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void propertiesLabelWhenApplicationNameContainsHyphen() throws Exception {
	Environment environment = new Environment("foo-bar", "default");
	environment.add(new PropertySource("foo", new HashMap<>()));
	when(this.repository.findOne("foo-bar", "default", "label", false))
			.thenReturn(this.environment);
	this.mvc.perform(MockMvcRequestBuilders.get("/label/foo-bar-default.properties"))
			.andExpect(MockMvcResultMatchers.status().isOk());
	verify(this.repository).findOne("foo-bar", "default", "label", false);
}
 
Example 9
Source File: CompositeEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testVersion() {
	PropertySource p1 = mock(PropertySource.class);
	doReturn("p1").when(p1).getName();
	PropertySource p2 = mock(PropertySource.class);
	doReturn("p2").when(p2).getName();
	String sLoc1 = "loc1";
	String sLoc2 = "loc2";
	Environment e1 = new Environment("app", "dev");
	e1.add(p1);
	e1.setVersion("1");
	e1.setState("state");
	Environment e2 = new Environment("app", "dev");
	e2.add(p2);
	e2.setVersion("2");
	e2.setState("state2");
	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[] { sLoc1, sLoc2 });
	List<EnvironmentRepository> repos = new ArrayList<EnvironmentRepository>();
	repos.add(new TestOrderedEnvironmentRepository(3, e1, loc1));
	List<EnvironmentRepository> repos2 = new ArrayList<EnvironmentRepository>();
	repos2.add(new TestOrderedEnvironmentRepository(3, e1, loc1));
	repos2.add(new TestOrderedEnvironmentRepository(3, e2, loc2));
	SearchPathCompositeEnvironmentRepository compositeRepo = new SearchPathCompositeEnvironmentRepository(
			repos);
	SearchPathCompositeEnvironmentRepository multiCompositeRepo = new SearchPathCompositeEnvironmentRepository(
			repos2);
	Environment env = compositeRepo.findOne("app", "dev", "label", false);
	assertThat(env.getVersion()).isEqualTo("1");
	assertThat(env.getState()).isEqualTo("state");
	Environment multiEnv = multiCompositeRepo.findOne("app", "dev", "label", false);
	assertThat(multiEnv.getVersion()).isEqualTo(null);
	assertThat(multiEnv.getState()).isEqualTo(null);

}
 
Example 10
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 11
Source File: CredhubEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
public Environment findOne(String application, String profilesList, String label) {
	if (StringUtils.isEmpty(profilesList)) {
		profilesList = DEFAULT_PROFILE;
	}
	if (StringUtils.isEmpty(label)) {
		label = DEFAULT_LABEL;
	}

	String[] profiles = StringUtils.commaDelimitedListToStringArray(profilesList);

	Environment environment = new Environment(application, profiles, label, null,
			null);
	for (String profile : profiles) {
		environment.add(new PropertySource(
				"credhub-" + application + "-" + profile + "-" + label,
				findProperties(application, profile, label)));
		if (!DEFAULT_APPLICATION.equals(application)) {
			addDefaultPropertySource(environment, DEFAULT_APPLICATION, profile,
					label);
		}
	}

	if (!Arrays.asList(profiles).contains(DEFAULT_PROFILE)) {
		addDefaultPropertySource(environment, application, DEFAULT_PROFILE, label);
	}

	if (!Arrays.asList(profiles).contains(DEFAULT_PROFILE)
			&& !DEFAULT_APPLICATION.equals(application)) {
		addDefaultPropertySource(environment, DEFAULT_APPLICATION, DEFAULT_PROFILE,
				label);
	}

	return environment;
}
 
Example 12
Source File: AwsS3EnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
public Environment findOne(String specifiedApplication, String specifiedProfiles,
		String specifiedLabel) {
	final String application = StringUtils.isEmpty(specifiedApplication)
			? serverProperties.getDefaultApplicationName() : specifiedApplication;
	final String profiles = StringUtils.isEmpty(specifiedProfiles)
			? serverProperties.getDefaultProfile() : specifiedProfiles;
	final String label = StringUtils.isEmpty(specifiedLabel)
			? serverProperties.getDefaultLabel() : specifiedLabel;

	String[] profileArray = parseProfiles(profiles);

	final Environment environment = new Environment(application, profileArray);
	environment.setLabel(label);

	for (String profile : profileArray) {
		S3ConfigFile s3ConfigFile = getS3ConfigFile(application, profile, label);
		if (s3ConfigFile != null) {
			environment.setVersion(s3ConfigFile.getVersion());

			final Properties config = s3ConfigFile.read();
			config.putAll(serverProperties.getOverrides());
			StringBuilder propertySourceName = new StringBuilder().append("s3:")
					.append(application);
			if (profile != null) {
				propertySourceName.append("-").append(profile);
			}
			environment
					.add(new PropertySource(propertySourceName.toString(), config));
		}
	}

	return environment;
}
 
Example 13
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 14
Source File: AbstractVaultEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
public Environment findOne(String application, String profile, String label) {
	String[] profiles = StringUtils.commaDelimitedListToStringArray(profile);
	List<String> scrubbedProfiles = scrubProfiles(profiles);

	List<String> keys = findKeys(application, scrubbedProfiles);

	Environment environment = new Environment(application, profiles, label, null,
			getWatchState());

	for (String key : keys) {
		// read raw 'data' key from vault
		String data = read(key);
		if (data != null) {
			// data is in json format of which, yaml is a superset, so parse
			final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
			yaml.setResources(new ByteArrayResource(data.getBytes()));
			Properties properties = yaml.getObject();

			if (!properties.isEmpty()) {
				environment.add(new PropertySource("vault:" + key, properties));
			}
		}
	}

	return environment;
}
 
Example 15
Source File: JdbcEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
public Environment findOne(String application, String profile, String label) {
	String config = application;
	if (StringUtils.isEmpty(label)) {
		label = "master";
	}
	if (StringUtils.isEmpty(profile)) {
		profile = "default";
	}
	if (!profile.startsWith("default")) {
		profile = "default," + profile;
	}
	String[] profiles = StringUtils.commaDelimitedListToStringArray(profile);
	Environment environment = new Environment(application, profiles, label, null,
			null);
	if (!config.startsWith("application")) {
		config = "application," + config;
	}
	List<String> applications = new ArrayList<String>(new LinkedHashSet<>(
			Arrays.asList(StringUtils.commaDelimitedListToStringArray(config))));
	List<String> envs = new ArrayList<String>(
			new LinkedHashSet<>(Arrays.asList(profiles)));
	Collections.reverse(applications);
	Collections.reverse(envs);
	for (String app : applications) {
		for (String env : envs) {
			Map<String, String> next = (Map<String, String>) this.jdbc.query(this.sql,
					new Object[] { app, env, label }, this.extractor);
			if (!next.isEmpty()) {
				environment.add(new PropertySource(app + "-" + env, next));
			}
		}
	}
	return environment;
}
 
Example 16
Source File: CustomCompositeEnvironmentRepositoryTests.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
public Environment findOne(String application, String profile, String label,
		boolean includeOrigin) {
	Environment e = new Environment("test", new String[0], "label", "version",
			"state");
	PropertySource p = new PropertySource(this.properties.getPropertySourceName(),
			new HashMap<>());
	e.add(p);
	return e;
}
 
Example 17
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);
}
 
Example 18
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 19
Source File: NacosEnvironmentRepository.java    From spring-cloud-alibaba with Apache License 2.0 4 votes vote down vote up
private Environment createEnvironment(ConfigInfo configInfo, String application,
		String profile) {

	Environment environment = new Environment(application, profile);

	Properties properties = createProperties(configInfo);

	String propertySourceName = String
			.format("Nacos[application : %s , profile : %s]", application, profile);

	PropertySource propertySource = new PropertySource(propertySourceName,
			properties);

	environment.add(propertySource);

	return environment;
}
 
Example 20
Source File: NacosEnvironmentRepository.java    From tech-weekly with Apache License 2.0 3 votes vote down vote up
@Override
public Environment findOne(String application, String profile, String label) {
    String dataId = application + "-" + profile + ".properties";
    String groupId = DEFAULT_GROUP;

    String content = getConfig(dataId, groupId);

    Environment environment = new Environment(application, profile);

    Properties properties = createProperties(content);

    environment.add(new PropertySource(dataId, properties));

    return environment;
}