org.springframework.boot.context.config.ConfigFileApplicationListener#org.springframework.cloud.config.environment.Environment源码实例Demo

下面列出了org.springframework.boot.context.config.ConfigFileApplicationListener#org.springframework.cloud.config.environment.Environment 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

private Environment postProcessResult(Environment result) {
    if (preprocessor == null) {
        return result;
    }

    result.getPropertySources().forEach(ps -> {
        Map<?, ?> source = ps.getSource();

        new HashSet<>(source.keySet()).forEach(key -> {
            Object value = ps.getSource().get(key);
            if (key instanceof String && value instanceof String) {
                String processedKey = preprocessor.process((String) key);
                String processedValue = preprocessor.process((String) value);

                if (!key.equals(processedKey) || !value.equals(processedValue)) {
                    logger.info("preprocessor processed config: key={}, value={}, " +
                            "REPLACED KEY={}, VALUE={}", key, value, processedKey, processedValue);
                    ps.getSource().remove(key);
                    ((Map<Object, Object>) source).put(processedKey, processedValue);
                }
            }
        });
    });
    return result;
}
 
源代码2 项目: Sentinel   文件: SentinelRuleLocator.java
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);
        }
    }
 
@Test
public void shouldRetrieveDefaultsWhenNoLabelNorProfileProvided() {
	stubCredentials("/my-application/default/master", "toggles", "key1", "value1");

	Environment environment = this.credhubEnvironmentRepository
			.findOne("my-application", null, null);

	assertThat(environment.getName()).isEqualTo("my-application");
	assertThat(environment.getProfiles()).containsExactly("default");
	assertThat(environment.getLabel()).isEqualTo("master");

	assertThat(environment.getPropertySources().size()).isEqualTo(1);
	assertThat(environment.getPropertySources().get(0).getName())
			.isEqualTo("credhub-my-application-default-master");
	assertThat(environment.getPropertySources().get(0).getSource())
			.isEqualTo(singletonMap("key1", "value1"));
}
 
@Test
public void testShouldReturnEnvironmentFromLocalBranchInCaseRemoteDeleted()
		throws Exception {
	JGitConfigServerTestData testData = JGitConfigServerTestData
			.prepareClonedGitRepository(TestConfiguration.class);

	String branchToDelete = "branchToDelete";
	testData.getServerGit().getGit().branchCreate().setName(branchToDelete).call();

	Environment environment = testData.getRepository().findOne("bar", "staging",
			"branchToDelete");
	assertThat(environment).isNotNull();

	testData.getServerGit().getGit().branchDelete().setBranchNames(branchToDelete)
			.call();
	testData.getRepository().findOne("bar", "staging", "branchToDelete");
	assertThat(environment).isNotNull();
}
 
@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;

}
 
@Test
public void mappingRepoWithProfileDefaultPatterns() throws IOException {
	String defaultRepoUri = ConfigServerTestUtils.prepareLocalRepo("config-repo");
	String test1RepoUri = ConfigServerTestUtils.prepareLocalRepo("test1-config-repo");

	Map<String, Object> repoMapping = new LinkedHashMap<String, Object>();
	repoMapping.put("spring.cloud.config.server.git.repos[test1].pattern",
			"*/staging");
	repoMapping.put("spring.cloud.config.server.git.repos[test1].uri", test1RepoUri);
	this.context = new SpringApplicationBuilder(TestConfiguration.class)
			.web(WebApplicationType.NONE)
			.properties("spring.cloud.config.server.git.uri:" + defaultRepoUri)
			.properties(repoMapping).run();
	EnvironmentRepository repository = this.context
			.getBean(EnvironmentRepository.class);
	Environment environment = repository.findOne("test1-svc", "staging,cloud",
			"master");
	assertThat(environment.getPropertySources().size()).isEqualTo(2);
}
 
@Override
public Environment findOne(String application, String profile, String label,
		boolean includeOrigin) {
	Environment env = new Environment(application, new String[] { profile }, label,
			null, null);
	if (this.environmentRepositories.size() == 1) {
		Environment envRepo = this.environmentRepositories.get(0).findOne(application,
				profile, label, includeOrigin);
		env.addAll(envRepo.getPropertySources());
		env.setVersion(envRepo.getVersion());
		env.setState(envRepo.getState());
	}
	else {
		for (EnvironmentRepository repo : environmentRepositories) {
			env.addAll(repo.findOne(application, profile, label, includeOrigin)
					.getPropertySources());
		}
	}
	return env;
}
 
@Test
public void update() throws Exception {
	String uri = ConfigServerTestUtils.prepareLocalSvnRepo(
			"src/test/resources/svn-config-repo", "target/config");
	this.context = new SpringApplicationBuilder(TestConfiguration.class)
			.web(WebApplicationType.NONE).profiles("subversion")
			.run("--spring.cloud.config.server.svn.uri=" + uri);
	EnvironmentRepository repository = this.context
			.getBean(EnvironmentRepository.class);
	Environment environment = repository.findOne("bar", "staging", "trunk");
	assertThat(environment.getPropertySources().get(0).getSource().get("foo"))
			.isEqualTo("bar");
	updateRepoForUpdate(uri);
	environment = repository.findOne("bar", "staging", "trunk");
	assertThat(environment.getPropertySources().get(0).getSource().get("foo"))
			.isEqualTo("foo");
}
 
@Test
public void mappingRepoWithJustUri() throws IOException {
	String defaultRepoUri = ConfigServerTestUtils.prepareLocalRepo("config-repo");
	String test1RepoUri = ConfigServerTestUtils.prepareLocalRepo("test1-config-repo");

	Map<String, Object> repoMapping = new LinkedHashMap<String, Object>();
	repoMapping.put("spring.cloud.config.server.git.repos.test1-svc.uri",
			test1RepoUri);
	this.context = new SpringApplicationBuilder(TestConfiguration.class)
			.web(WebApplicationType.NONE)
			.properties("spring.cloud.config.server.git.uri:" + defaultRepoUri)
			.properties(repoMapping).run();
	EnvironmentRepository repository = this.context
			.getBean(EnvironmentRepository.class);
	Environment environment = repository.findOne("test1-svc", "staging", "master");
	assertThat(environment.getPropertySources().size()).isEqualTo(2);
}
 
@Test(expected = NoSuchLabelException.class)
public void testShouldFailIfRemoteBranchWasDeleted() throws Exception {
	JGitConfigServerTestData testData = JGitConfigServerTestData
			.prepareClonedGitRepository(Collections.singleton(
					"spring.cloud.config.server.git.deleteUntrackedBranches=true"),
					TestConfiguration.class);

	String branchToDelete = "branchToDelete";
	testData.getServerGit().getGit().branchCreate().setName(branchToDelete).call();

	// checkout and simulate regular flow
	Environment environment = testData.getRepository().findOne("bar", "staging",
			"branchToDelete");
	assertThat(environment).isNotNull();

	// remove branch
	testData.getServerGit().getGit().branchDelete().setBranchNames(branchToDelete)
			.call();

	// test
	testData.getRepository().findOne("bar", "staging", "branchToDelete");
}
 
@Test
public void mappingRepoWithProfiles() throws IOException {
	String defaultRepoUri = ConfigServerTestUtils.prepareLocalRepo("config-repo");
	String test1RepoUri = ConfigServerTestUtils.prepareLocalRepo("test1-config-repo");

	Map<String, Object> repoMapping = new LinkedHashMap<String, Object>();
	repoMapping.put("spring.cloud.config.server.git.repos[test1].pattern[0]",
			"*/staging,*");
	repoMapping.put("spring.cloud.config.server.git.repos[test1].pattern[1]",
			"*/*,staging");
	repoMapping.put("spring.cloud.config.server.git.repos[test1].pattern[2]",
			"*/staging");
	repoMapping.put("spring.cloud.config.server.git.repos[test1].uri", test1RepoUri);
	this.context = new SpringApplicationBuilder(TestConfiguration.class)
			.web(WebApplicationType.NONE)
			.properties("spring.cloud.config.server.git.uri:" + defaultRepoUri)
			.properties(repoMapping).run();
	EnvironmentRepository repository = this.context
			.getBean(EnvironmentRepository.class);
	Environment environment = repository.findOne("test1-svc", "cloud,staging",
			"master");
	assertThat(environment.getPropertySources().size()).isEqualTo(2);
	environment = repository.findOne("test1-svc", "staging,cloud", "master");
	assertThat(environment.getPropertySources().size()).isEqualTo(2);
}
 
@Test
public void findOne_FileAddedToRepo_FindOneSuccess() throws Exception {
	ConfigServerTestUtils.prepareLocalRepo();
	String uri = ConfigServerTestUtils.copyLocalRepo("config-copy");
	this.context = new SpringApplicationBuilder(TestConfiguration.class)
			.web(WebApplicationType.NONE)
			.run("--spring.cloud.config.server.git.uri=" + uri,
					"--spring.cloud.config.server.git.cloneOnStart=true");
	EnvironmentRepository repository = this.context
			.getBean(EnvironmentRepository.class);
	Environment environment = repository.findOne("bar", "staging", "master");
	assertThat(environment.getPropertySources().get(0).getSource().get("foo"))
			.isEqualTo("bar");
	Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile());
	git.checkout().setName("master").call();
	StreamUtils.copy("foo: foo", Charset.defaultCharset(),
			new FileOutputStream(ResourceUtils.getFile(uri + "/bar.properties")));
	git.add().addFilepattern("bar.properties").call();
	git.commit().setMessage("Updated for pull").call();
	environment = repository.findOne("bar", "staging", "master");
	assertThat(environment.getPropertySources().get(0).getSource().get("foo"))
			.isEqualTo("foo");
}
 
@Override
public Environment findOne(String application, String profile, String label,
		boolean includeOrigin) {

	if (this.pattern == null || this.pattern.length == 0) {
		return null;
	}

	if (PatternMatchUtils.simpleMatch(this.pattern,
			application + "/" + profile)) {
		return super.findOne(application, profile, label, includeOrigin);
	}

	return null;

}
 
@Test
public void findOne_CloneOnStartTrue_FindOneSuccess() throws Exception {
	ConfigServerTestUtils.prepareLocalRepo();
	String uri = ConfigServerTestUtils.copyLocalRepo("config-copy");
	this.context = new SpringApplicationBuilder(TestConfiguration.class)
			.web(WebApplicationType.NONE)
			.run("--spring.cloud.config.server.git.uri=" + uri,
					"--spring.cloud.config.server.git.cloneOnStart=true");
	EnvironmentRepository repository = this.context
			.getBean(JGitEnvironmentRepository.class);
	assertThat(((JGitEnvironmentRepository) repository).isCloneOnStart()).isTrue();
	Environment environment = repository.findOne("bar", "staging", "master");
	assertThat(environment.getPropertySources().size()).isEqualTo(2);
	assertThat(environment.getName()).isEqualTo("bar");
	assertThat(environment.getProfiles()).isEqualTo(new String[] { "staging" });
	assertThat(environment.getLabel()).isEqualTo("master");
}
 
@Test
public void contextLoads() {
	ResponseEntity<Environment> response = new TestRestTemplate().exchange(
			"http://localhost:" + this.port + "/foo/development/", HttpMethod.GET,
			getV2AcceptEntity(), Environment.class);
	Environment environment = response.getBody();
	assertThat(3).isEqualTo(environment.getPropertySources().size());
	assertThat("overrides")
			.isEqualTo(environment.getPropertySources().get(0).getName());
	assertThat(environment.getPropertySources().get(1).getName()
			.contains("config-repo")
			&& !environment.getPropertySources().get(1).getName()
					.contains("svn-config-repo")).isTrue();
	assertThat(environment.getPropertySources().get(2).getName()
			.contains("svn-config-repo")).isTrue();
	ConfigServerTestUtils.assertConfigEnabled(environment);
}
 
@Test
public void contextLoads() {
	ResponseEntity<Environment> response = new TestRestTemplate().exchange(
			"http://localhost:" + this.port + "/foo/development/", HttpMethod.GET,
			getV2AcceptEntity(), Environment.class);
	Environment environment = response.getBody();
	assertThat(environment.getPropertySources()).hasSize(3);
	assertThat("overrides")
			.isEqualTo(environment.getPropertySources().get(0).getName());
	assertThat(environment.getPropertySources().get(1).getName()
			.contains("config-repo")
			&& !environment.getPropertySources().get(1).getName()
					.contains("svn-config-repo")).isTrue();
	assertThat(environment.getPropertySources().get(2).getName()
			.contains("svn-config-repo")).isTrue();
	ConfigServerTestUtils.assertConfigEnabled(environment);
}
 
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));
        }
    }
}
 
@Test
public void findWithDefaultProfileUsingSuffix() throws UnsupportedEncodingException {
	setupS3("foo-default.yml", yamlContent);

	final Environment env = envRepo.findOne("foo", null, null);

	assertExpectedEnvironment(env, "foo", null, null, 1, "default", null);
}
 
@Test
public void testFindOneDefaultKeySetAndDifferentToMultipleApplications() {
	VaultKeyValueOperations keyValueTemplate = mock(VaultKeyValueOperations.class);
	when(keyValueTemplate.get("myapp"))
			.thenReturn(withVaultResponse("myapp-foo", "myapp-bar"));
	when(keyValueTemplate.get("yourapp"))
			.thenReturn(withVaultResponse("yourapp-foo", "yourapp-bar"));
	when(keyValueTemplate.get("mydefaultkey"))
			.thenReturn(withVaultResponse("def-foo", "def-bar"));

	SpringVaultEnvironmentRepository repo = new SpringVaultEnvironmentRepository(
			mockHttpRequest(), new EnvironmentWatch.Default(),
			new VaultEnvironmentProperties(), keyValueTemplate);
	repo.setDefaultKey("mydefaultkey");

	Environment e = repo.findOne("myapp,yourapp", null, null);
	assertThat(e.getName()).as("Name should be the same as the application argument")
			.isEqualTo("myapp,yourapp");
	assertThat(e.getPropertySources()).as(
			"Properties for specified applications and default application with key 'mydefaultkey' should be returned")
			.hasSize(3);

	assertThat(e.getPropertySources().get(0).getSource()).as(
			"Properties for first specified application should be returned in priority position")
			.containsOnly((Map.Entry) entry("yourapp-foo", "yourapp-bar"));

	assertThat(e.getPropertySources().get(1).getSource()).as(
			"Properties for second specified application should be returned in priority position")
			.containsOnly((Map.Entry) entry("myapp-foo", "myapp-bar"));

	assertThat(e.getPropertySources().get(2).getSource()).as(
			"Properties for default application with key 'mydefaultkey' should be returned in second position")
			.containsOnly((Map.Entry) entry("def-foo", "def-bar"));
}
 
@Test
public void defaultRepoNested() throws IOException {
	String uri = ConfigServerTestUtils.prepareLocalRepo("another-config-repo");
	this.repository.setUri(uri);
	this.repository.setSearchPaths(new String[] { "sub" });
	Environment environment = this.repository.findOne("bar", "staging", "master");
	assertThat(environment.getPropertySources().size()).isEqualTo(2);
	assertThat(environment.getPropertySources().get(0).getName())
			.isEqualTo(this.repository.getUri() + "/sub/application.yml");
	assertVersion(environment);
}
 
@Test
public void server() {
	mongoTemplate.dropCollection("testapp");
	MongoPropertySource ps = new MongoPropertySource();
	ps.getSource().put("testkey", "testval");
	mongoTemplate.save(ps, "testapp");
	Environment environment = new TestRestTemplate().getForObject("http://localhost:"
			+ port + "/testapp/default", Environment.class);
	assertEquals("testapp-default", environment.getPropertySources().get(0).getName());
	assertEquals(1, environment.getPropertySources().size());
	assertEquals(true, environment.getPropertySources().get(0).getSource().containsKey("testkey"));
	assertEquals("testval", environment.getPropertySources().get(0).getSource().get("testkey"));
}
 
@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);
}
 
@Test
public void defaultRepoBranch() {
	Environment environment = this.repository.findOne("bar", "staging", "raw");
	assertThat(environment.getPropertySources().size()).isEqualTo(2);
	assertThat(environment.getPropertySources().get(0).getName())
			.isEqualTo(this.repository.getUri() + "/bar.properties");
	assertVersion(environment);
}
 
@Test
public void whenDecryptResource_thenAllEncryptedValuesDecrypted() throws Exception {
	// given
	Environment environment = new Environment("name", "profile", "label");
	File file = ResourceUtils.getFile("classpath:resource-encryptor/test.json");
	String text = new String(Files.readAllBytes(file.toPath()));

	// when
	String decyptedResource = encryptor.decrypt(text, environment);

	// then
	assertThat(decyptedResource.contains("{cipher}")).isFalse();
}
 
@Test
public void placeholdersApplicationAndProfile() {
	this.repository.setSearchLocations("classpath:/test/{profile}/{application}/");
	Environment environment = this.repository.findOne("app", "dev", "master");
	assertThat(environment.getPropertySources().size()).isEqualTo(1);
	assertThat(environment.getPropertySources().get(0).getSource().get("foo"))
			.isEqualTo("app");
}
 
@Test
public void sunnyDayWithLabel() {
	Environment body = new Environment("app", "master");
	mockRequestResponseWithLabel(new ResponseEntity<>(body, HttpStatus.OK), "v1.0.0");
	this.locator.setRestTemplate(this.restTemplate);
	TestPropertyValues.of("spring.cloud.config.label:v1.0.0")
			.applyTo(this.environment);
	assertThat(this.locator.locateCollection(this.environment)).isNotNull();
}
 
@Test
public void mappingRepo() {
	Environment environment = this.repository.findOne("test1-config-repo", "staging",
			"master");
	assertThat(environment.getPropertySources().size()).isEqualTo(1);
	assertThat(environment.getPropertySources().get(0).getName())
			.isEqualTo(getUri("*").replace("{application}", "test1-config-repo")
					+ "/application.yml");
	assertVersion(environment);
}
 
@Test
public void placeholderInSearchPath() throws IOException {
	String uri = ConfigServerTestUtils.prepareLocalRepo("another-config-repo");
	this.repository.setUri(uri);
	this.repository.setSearchPaths(new String[] { "{application}" });
	Environment environment = this.repository.findOne("sub", "staging", "master");
	assertThat(environment.getPropertySources().size()).isEqualTo(1);
	assertThat(environment.getPropertySources().get(0).getName())
			.isEqualTo(this.repository.getUri() + "/sub/application.yml");
	assertVersion(environment);
}
 
源代码29 项目: spring-cloud-config   文件: ResourceController.java
private synchronized byte[] binary(ServletWebRequest request, String name,
		String profile, String label, String path) throws IOException {
	name = Environment.normalize(name);
	label = Environment.normalize(label);
	Resource resource = this.resourceRepository.findOne(name, profile, label, path);
	if (checkNotModified(request, resource)) {
		// Content was not modified. Just return.
		return null;
	}
	// TODO: is this line needed for side effects?
	prepareEnvironment(this.environmentRepository.findOne(name, profile, label));
	try (InputStream is = resource.getInputStream()) {
		return StreamUtils.copyToByteArray(is);
	}
}
 
public static StandardEnvironment prepareEnvironment(Environment environment) {
	StandardEnvironment standardEnvironment = new StandardEnvironment();
	standardEnvironment.getPropertySources()
			.remove(StandardEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME);
	standardEnvironment.getPropertySources()
			.remove(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME);
	standardEnvironment.getPropertySources()
			.addFirst(new EnvironmentPropertySource(environment));
	return standardEnvironment;
}