Bumping versions

This commit is contained in:
buildmaster
2024-07-23 10:34:53 +00:00
parent c1e60f94f9
commit 2872adf32e
156 changed files with 1648 additions and 1300 deletions

View File

@@ -103,19 +103,19 @@ class ConfigClientHints implements RuntimeHintsRegistrar {
return;
}
hints.reflection()
.registerType(TypeReference.of(ConfigClientAutoConfiguration.class),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference.of(ConfigDataLocation.class),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS))
.registerType(TypeReference.of("org.springframework.boot.context.config.ConfigDataProperties"),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.DECLARED_FIELDS, MemberCategory.INTROSPECT_DECLARED_METHODS))
.registerType(TypeReference.of(org.springframework.cloud.config.environment.Environment.class),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS))
.registerType(TypeReference.of(PropertySource.class),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS));
.registerType(TypeReference.of(ConfigClientAutoConfiguration.class),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference.of(ConfigDataLocation.class),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS))
.registerType(TypeReference.of("org.springframework.boot.context.config.ConfigDataProperties"),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.DECLARED_FIELDS, MemberCategory.INTROSPECT_DECLARED_METHODS))
.registerType(TypeReference.of(org.springframework.cloud.config.environment.Environment.class),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS))
.registerType(TypeReference.of(PropertySource.class),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS));
}
}

View File

@@ -114,18 +114,19 @@ public class ConfigClientRequestTemplateFactory {
SSLContextFactory factory = new SSLContextFactory(client.getTls());
SSLContext sslContext = factory.createSSLContext();
SSLConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder = SSLConnectionSocketFactoryBuilder
.create();
.create();
sslConnectionSocketFactoryBuilder.setSslContext(sslContext);
SocketConfig.Builder socketBuilder = createSocketBuilderForTls(client);
PoolingHttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultSocketConfig(socketBuilder.build())
.setSSLSocketFactory(sslConnectionSocketFactoryBuilder.build()).build();
.setDefaultSocketConfig(socketBuilder.build())
.setSSLSocketFactory(sslConnectionSocketFactoryBuilder.build())
.build();
return connectionManager;
}
protected SocketConfig.Builder createSocketBuilderForTls(ConfigClientProperties client) {
SocketConfig.Builder socketBuilder = SocketConfig.custom()
.setSoTimeout(Timeout.of(client.getRequestReadTimeout(), TimeUnit.MILLISECONDS));
.setSoTimeout(Timeout.of(client.getRequestReadTimeout(), TimeUnit.MILLISECONDS));
return socketBuilder;
}

View File

@@ -126,7 +126,7 @@ public class ConfigServerConfigDataLoader implements ConfigDataLoader<ConfigServ
// result.getPropertySources() can be null if using xml
if (result.getPropertySources() != null) {
for (org.springframework.cloud.config.environment.PropertySource source : result
.getPropertySources()) {
.getPropertySources()) {
@SuppressWarnings("unchecked")
Map<String, Object> map = translateOrigins(source.getName(),
(Map<String, Object>) source.getSource());
@@ -222,7 +222,7 @@ public class ConfigServerConfigDataLoader implements ConfigDataLoader<ConfigServ
}
if (logger.isDebugEnabled()) {
List<org.springframework.cloud.config.environment.PropertySource> propertySourceList = result
.getPropertySources();
.getPropertySources();
if (propertySourceList != null) {
int propertyCount = 0;
for (org.springframework.cloud.config.environment.PropertySource propertySource : propertySourceList) {
@@ -277,7 +277,7 @@ public class ConfigServerConfigDataLoader implements ConfigDataLoader<ConfigServ
String[] uris;
boolean discoveryEnabled = properties.getDiscovery().isEnabled();
ConfigClientProperties bootstrapConfigClientProperties = context.getBootstrapContext()
.get(ConfigClientProperties.class);
.get(ConfigClientProperties.class);
// In the case where discovery is enabled we need to extract the config server
// uris, username, and password
// from the properties from the context. These are set in
@@ -305,7 +305,7 @@ public class ConfigServerConfigDataLoader implements ConfigDataLoader<ConfigServ
List<MediaType> acceptHeader = Collections.singletonList(MediaType.parseMediaType(properties.getMediaType()));
ConfigClientRequestTemplateFactory requestTemplateFactory = context.getBootstrapContext()
.get(ConfigClientRequestTemplateFactory.class);
.get(ConfigClientRequestTemplateFactory.class);
for (int i = 0; i < noOfUrls; i++) {
String username;

View File

@@ -61,7 +61,7 @@ public class ConfigServerConfigDataLocationResolver
*/
public static final String PREFIX = "configserver:";
static final boolean RSA_IS_PRESENT = ClassUtils
.isPresent("org.springframework.security.rsa.crypto.RsaSecretEncryptor", null);
.isPresent("org.springframework.security.rsa.crypto.RsaSecretEncryptor", null);
private final Log log;
@@ -116,10 +116,11 @@ public class ConfigServerConfigDataLocationResolver
ConfigClientProperties configClientProperties;
if (context.getBootstrapContext().isRegistered(ConfigClientProperties.class)) {
configClientProperties = binder
.bind(ConfigClientProperties.PREFIX, Bindable.of(ConfigClientProperties.class), bindHandler)
.orElseGet(ConfigClientProperties::new);
.bind(ConfigClientProperties.PREFIX, Bindable.of(ConfigClientProperties.class), bindHandler)
.orElseGet(ConfigClientProperties::new);
boolean discoveryEnabled = context.getBinder()
.bind(CONFIG_DISCOVERY_ENABLED, Bindable.of(Boolean.class), getBindHandler(context)).orElse(false);
.bind(CONFIG_DISCOVERY_ENABLED, Bindable.of(Boolean.class), getBindHandler(context))
.orElse(false);
// In the case where discovery is enabled we need to extract the config server
// uris, username, and password
// from the properties from the context. These are set in
@@ -127,7 +128,7 @@ public class ConfigServerConfigDataLocationResolver
// be called the first time we fetch configuration.
if (discoveryEnabled) {
ConfigClientProperties bootstrapConfigClientProperties = context.getBootstrapContext()
.get(ConfigClientProperties.class);
.get(ConfigClientProperties.class);
configClientProperties.setUri(bootstrapConfigClientProperties.getUri());
configClientProperties.setPassword(bootstrapConfigClientProperties.getPassword());
@@ -136,14 +137,14 @@ public class ConfigServerConfigDataLocationResolver
}
else {
configClientProperties = binder
.bind(ConfigClientProperties.PREFIX, Bindable.of(ConfigClientProperties.class), bindHandler)
.orElseGet(ConfigClientProperties::new);
.bind(ConfigClientProperties.PREFIX, Bindable.of(ConfigClientProperties.class), bindHandler)
.orElseGet(ConfigClientProperties::new);
}
if (!StringUtils.hasText(configClientProperties.getName())
|| "application".equals(configClientProperties.getName())) {
// default to spring.application.name if name isn't set
String applicationName = binder.bind("spring.application.name", Bindable.of(String.class), bindHandler)
.orElse("application");
.orElse("application");
configClientProperties.setName(applicationName);
}
@@ -151,7 +152,7 @@ public class ConfigServerConfigDataLocationResolver
holder.properties = configClientProperties;
// bind retry, override later
holder.retryProperties = binder.bind(RetryProperties.PREFIX, RetryProperties.class)
.orElseGet(RetryProperties::new);
.orElseGet(RetryProperties::new);
if (StringUtils.hasText(uris)) {
String[] uri = StringUtils.commaDelimitedListToStringArray(uris);
@@ -168,19 +169,24 @@ public class ConfigServerConfigDataLocationResolver
}
if (StringUtils.hasText(paramStr)) {
Properties properties = StringUtils
.splitArrayElementsIntoProperties(StringUtils.delimitedListToStringArray(paramStr, "&"), "=");
.splitArrayElementsIntoProperties(StringUtils.delimitedListToStringArray(paramStr, "&"), "=");
if (properties != null) {
PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
map.from(() -> properties.getProperty("fail-fast")).as(Boolean::valueOf)
.to(configClientProperties::setFailFast);
map.from(() -> properties.getProperty("max-attempts")).as(Integer::valueOf)
.to(holder.retryProperties::setMaxAttempts);
map.from(() -> properties.getProperty("max-interval")).as(Long::valueOf)
.to(holder.retryProperties::setMaxInterval);
map.from(() -> properties.getProperty("multiplier")).as(Double::valueOf)
.to(holder.retryProperties::setMultiplier);
map.from(() -> properties.getProperty("initial-interval")).as(Long::valueOf)
.to(holder.retryProperties::setInitialInterval);
map.from(() -> properties.getProperty("fail-fast"))
.as(Boolean::valueOf)
.to(configClientProperties::setFailFast);
map.from(() -> properties.getProperty("max-attempts"))
.as(Integer::valueOf)
.to(holder.retryProperties::setMaxAttempts);
map.from(() -> properties.getProperty("max-interval"))
.as(Long::valueOf)
.to(holder.retryProperties::setMaxInterval);
map.from(() -> properties.getProperty("multiplier"))
.as(Double::valueOf)
.to(holder.retryProperties::setMultiplier);
map.from(() -> properties.getProperty("initial-interval"))
.as(Long::valueOf)
.to(holder.retryProperties::setInitialInterval);
}
}
configClientProperties.setUri(uri);
@@ -233,8 +239,10 @@ public class ConfigServerConfigDataLocationResolver
ConfigurableBootstrapContext bootstrapContext = resolverContext.getBootstrapContext();
bootstrapContext.register(ConfigClientProperties.class,
InstanceSupplier.of(properties).withScope(BootstrapRegistry.Scope.PROTOTYPE));
bootstrapContext.addCloseListener(event -> event.getApplicationContext().getBeanFactory().registerSingleton(
"configDataConfigClientProperties", event.getBootstrapContext().get(ConfigClientProperties.class)));
bootstrapContext.addCloseListener(event -> event.getApplicationContext()
.getBeanFactory()
.registerSingleton("configDataConfigClientProperties",
event.getBootstrapContext().get(ConfigClientProperties.class)));
bootstrapContext.registerIfAbsent(ConfigClientRequestTemplateFactory.class,
context -> new ConfigClientRequestTemplateFactory(log, context.get(ConfigClientProperties.class)));
@@ -259,18 +267,20 @@ public class ConfigServerConfigDataLocationResolver
resource.setRetryProperties(propertyHolder.retryProperties);
boolean discoveryEnabled = resolverContext.getBinder()
.bind(CONFIG_DISCOVERY_ENABLED, Bindable.of(Boolean.class), getBindHandler(resolverContext))
.orElse(false);
.bind(CONFIG_DISCOVERY_ENABLED, Bindable.of(Boolean.class), getBindHandler(resolverContext))
.orElse(false);
boolean retryEnabled = resolverContext.getBinder().bind(ConfigClientProperties.PREFIX + ".fail-fast",
Bindable.of(Boolean.class), getBindHandler(resolverContext)).orElse(false);
boolean retryEnabled = resolverContext.getBinder()
.bind(ConfigClientProperties.PREFIX + ".fail-fast", Bindable.of(Boolean.class),
getBindHandler(resolverContext))
.orElse(false);
if (discoveryEnabled) {
log.debug(LogMessage.format("discovery enabled"));
// register ConfigServerInstanceMonitor
bootstrapContext.registerIfAbsent(ConfigServerInstanceMonitor.class, context -> {
ConfigServerInstanceProvider.Function function = context
.get(ConfigServerInstanceProvider.Function.class);
.get(ConfigServerInstanceProvider.Function.class);
ConfigServerInstanceProvider instanceProvider;
if (ConfigClientRetryBootstrapper.RETRY_IS_PRESENT && retryEnabled) {
@@ -301,9 +311,10 @@ public class ConfigServerConfigDataLocationResolver
// config client uri
bootstrapContext.addCloseListener(event -> {
ConfigServerInstanceMonitor configServerInstanceMonitor = event.getBootstrapContext()
.get(ConfigServerInstanceMonitor.class);
event.getApplicationContext().getBeanFactory().registerSingleton("configServerInstanceMonitor",
configServerInstanceMonitor);
.get(ConfigServerInstanceMonitor.class);
event.getApplicationContext()
.getBeanFactory()
.registerSingleton("configServerInstanceMonitor", configServerInstanceMonitor);
});
}

View File

@@ -173,8 +173,10 @@ public class ConfigServerConfigDataResource extends ConfigDataResource {
@Override
public String toString() {
return new ToStringCreator(this).append("uris", properties.getUri()).append("optional", optional)
.append("profiles", getProfiles()).toString();
return new ToStringCreator(this).append("uris", properties.getUri())
.append("optional", optional)
.append("profiles", getProfiles())
.toString();
}

View File

@@ -78,11 +78,12 @@ public class ConfigServerHealthIndicator extends AbstractHealthIndicator {
long accessTime = System.currentTimeMillis();
if (isCacheStale(accessTime)) {
this.lastAccess = accessTime;
this.cached = this.environment.getPropertySources().stream()
.filter(p -> p.getName().startsWith(CONFIG_CLIENT_PROPERTYSOURCE_NAME)
|| p.getName().startsWith(BOOTSTRAP_PROPERTY_SOURCE_NAME + "-")
|| p.getName().startsWith(PREFIX))
.collect(Collectors.toList());
this.cached = this.environment.getPropertySources()
.stream()
.filter(p -> p.getName().startsWith(CONFIG_CLIENT_PROPERTYSOURCE_NAME)
|| p.getName().startsWith(BOOTSTRAP_PROPERTY_SOURCE_NAME + "-")
|| p.getName().startsWith(PREFIX))
.collect(Collectors.toList());
}
return this.cached;
}

View File

@@ -77,8 +77,10 @@ public class ConfigServiceBootstrapConfiguration {
policy.setInitialInterval(properties.getInitialInterval());
policy.setMultiplier(properties.getMultiplier());
policy.setMaxInterval(properties.getMaxInterval());
return RetryInterceptorBuilder.stateless().backOffPolicy(policy).maxAttempts(properties.getMaxAttempts())
.build();
return RetryInterceptorBuilder.stateless()
.backOffPolicy(policy)
.maxAttempts(properties.getMaxAttempts())
.build();
}
}

View File

@@ -91,7 +91,8 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator
if (environment.getActiveProfiles().length > 0) {
List<String> finalCombinedProfiles = combinedProfiles;
List<String> filteredActiveProfiles = Stream.of(environment.getActiveProfiles())
.filter(s -> !finalCombinedProfiles.contains(s)).collect(Collectors.toList());
.filter(s -> !finalCombinedProfiles.contains(s))
.collect(Collectors.toList());
combinedProfiles.addAll(filteredActiveProfiles);
}
else if (environment.getDefaultProfiles().length > 0 && combinedProfiles.isEmpty()) {

View File

@@ -39,10 +39,11 @@ public final class RetryTemplateFactory {
}
public static RetryTemplate create(RetryProperties properties, Log log) {
RetryTemplate retryTemplate = RetryTemplate
.builder().maxAttempts(properties.getMaxAttempts()).exponentialBackoff(properties.getInitialInterval(),
properties.getMultiplier(), properties.getMaxInterval(), properties.isUseRandomPolicy())
.build();
RetryTemplate retryTemplate = RetryTemplate.builder()
.maxAttempts(properties.getMaxAttempts())
.exponentialBackoff(properties.getInitialInterval(), properties.getMultiplier(),
properties.getMaxInterval(), properties.isUseRandomPolicy())
.build();
try {
field.set(retryTemplate, log);
}

View File

@@ -66,12 +66,13 @@ public abstract class BaseDiscoveryClientConfigServiceBootstrapConfigurationTest
void givenDiscoveryClientReturnsInfoOnThirdTry() {
given(this.client.getInstances(DEFAULT_CONFIG_SERVER)).willReturn(Collections.<ServiceInstance>emptyList())
.willReturn(Collections.<ServiceInstance>emptyList()).willReturn(Collections.singletonList(this.info));
.willReturn(Collections.<ServiceInstance>emptyList())
.willReturn(Collections.singletonList(this.info));
}
void expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup() {
assertThat(this.context.getBeanNamesForType(DiscoveryClientConfigServiceBootstrapConfiguration.class).length)
.isEqualTo(1);
.isEqualTo(1);
}
void expectConfigClientPropertiesHasDefaultConfiguration() {

View File

@@ -36,37 +36,41 @@ public class ConfigClientAutoConfigurationTests {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
ConfigClientAutoConfiguration.class);
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, ConfigClientProperties.class).length)
.isEqualTo(1);
.isEqualTo(1);
context.close();
}
@Test
public void withParent() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(ConfigClientAutoConfiguration.class)
.child(Object.class).web(WebApplicationType.NONE).properties("spring.cloud.bootstrap.enabled=true")
.run();
.child(Object.class)
.web(WebApplicationType.NONE)
.properties("spring.cloud.bootstrap.enabled=true")
.run();
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, ConfigClientProperties.class).length)
.isEqualTo(1);
.isEqualTo(1);
context.close();
}
@Test
public void invalidApplicationNameOverrideWithFailFastEnabledFailsToStartup() {
SpringApplication application = new SpringApplicationBuilder(ConfigClientAutoConfiguration.class)
.web(WebApplicationType.NONE).properties("spring.cloud.config.fail-fast=true",
"spring.cloud.bootstrap.enabled=true", "spring.cloud.config.name=application-service")
.application();
.web(WebApplicationType.NONE)
.properties("spring.cloud.config.fail-fast=true", "spring.cloud.bootstrap.enabled=true",
"spring.cloud.config.name=application-service")
.application();
assertThatThrownBy(application::run).isInstanceOf(InvalidApplicationNameException.class).extracting("value")
.isEqualTo("application-service");
assertThatThrownBy(application::run).isInstanceOf(InvalidApplicationNameException.class)
.extracting("value")
.isEqualTo("application-service");
}
@Test
public void invalidApplicationNameOverrideWithFailFastDisabledStartsUpButNoConfigServerPropertiesAreLoaded() {
SpringApplication application = new SpringApplicationBuilder(ConfigClientAutoConfiguration.class)
.web(WebApplicationType.NONE)
.properties("spring.cloud.config.name=application-service", "spring.cloud.bootstrap.enabled=true")
.application();
.web(WebApplicationType.NONE)
.properties("spring.cloud.config.name=application-service", "spring.cloud.bootstrap.enabled=true")
.application();
ConfigurableApplicationContext context = application.run();
@@ -78,20 +82,22 @@ public class ConfigClientAutoConfigurationTests {
@Test
public void invalidApplicationNameWithFailFastEnabledFailsToStartup() {
SpringApplication application = new SpringApplicationBuilder(ConfigClientAutoConfiguration.class)
.web(WebApplicationType.NONE).properties("spring.cloud.config.fail-fast=true",
"spring.cloud.bootstrap.enabled=true", "spring.application.name=application-service")
.application();
.web(WebApplicationType.NONE)
.properties("spring.cloud.config.fail-fast=true", "spring.cloud.bootstrap.enabled=true",
"spring.application.name=application-service")
.application();
assertThatThrownBy(application::run).isInstanceOf(InvalidApplicationNameException.class).extracting("value")
.isEqualTo("application-service");
assertThatThrownBy(application::run).isInstanceOf(InvalidApplicationNameException.class)
.extracting("value")
.isEqualTo("application-service");
}
@Test
public void invalidApplicationNameWithFailFastDisabledStartsUpButNoConfigServerPropertiesAreLoaded() {
SpringApplication application = new SpringApplicationBuilder(ConfigClientAutoConfiguration.class)
.web(WebApplicationType.NONE)
.properties("spring.application.name=application-service", "spring.cloud.bootstrap.enabled=true")
.application();
.web(WebApplicationType.NONE)
.properties("spring.application.name=application-service", "spring.cloud.bootstrap.enabled=true")
.application();
ConfigurableApplicationContext context = application.run();

View File

@@ -65,10 +65,12 @@ public class ConfigClientConfigDataLoaderTest {
when(responseEntity.getBody()).thenReturn(environment);
when(rest.exchange(eq("http://localhost:8888/{name}/{profile}"), eq(HttpMethod.GET),
ArgumentMatchers.any(HttpEntity.class), eq(Environment.class), eq("application"),
ArgumentMatchers.<String>any())).thenReturn(responseEntity);
ArgumentMatchers.<String>any()))
.thenReturn(responseEntity);
when(rest.exchange(eq("http://localhost:8888/{name}/{profile}"), eq(HttpMethod.GET),
ArgumentMatchers.any(HttpEntity.class), eq(Environment.class), eq("foo"),
ArgumentMatchers.<String>any())).thenReturn(responseEntity);
ArgumentMatchers.<String>any()))
.thenReturn(responseEntity);
context = setup(rest).run();
verify(rest).exchange(eq("http://localhost:8888/{name}/{profile}"), eq(HttpMethod.GET),
ArgumentMatchers.any(HttpEntity.class), eq(Environment.class), eq("application"),
@@ -86,7 +88,7 @@ public class ConfigClientConfigDataLoaderTest {
SpringApplicationBuilder setup(RestTemplate restTemplate, String... env) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(
DiscoveryClientConfigDataConfigurationTests.TestConfig.class)
.properties("spring.config.import=classpath:applicationname.yaml, optional:configserver:");
.properties("spring.config.import=classpath:applicationname.yaml, optional:configserver:");
builder.addBootstrapRegistryInitializer(
registry -> registry.register(RestTemplate.class, context -> restTemplate));

View File

@@ -180,7 +180,7 @@ public class ConfigClientPropertiesTests {
properties.setMultipleUriStrategy(MultipleUriStrategy.CONNECTION_TIMEOUT_ONLY);
assertThat(properties.getMultipleUriStrategy()).isNotNull();
assertThat(properties.getMultipleUriStrategy().name())
.isEqualTo(MultipleUriStrategy.CONNECTION_TIMEOUT_ONLY.name());
.isEqualTo(MultipleUriStrategy.CONNECTION_TIMEOUT_ONLY.name());
}
}

View File

@@ -32,13 +32,15 @@ public class ConfigServerBootstrapConfigurationTests {
public void withHealthIndicator() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
PropertySourceBootstrapConfiguration.class, ConfigServiceBootstrapConfiguration.class)
.child(ConfigClientAutoConfiguration.class).properties("spring.cloud.bootstrap.enabled=true")
.web(WebApplicationType.NONE).run();
.child(ConfigClientAutoConfiguration.class)
.properties("spring.cloud.bootstrap.enabled=true")
.web(WebApplicationType.NONE)
.run();
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, ConfigClientProperties.class).length)
.isEqualTo(1);
.isEqualTo(1);
assertThat(
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context, ConfigServerHealthIndicator.class).length)
.isEqualTo(1);
.isEqualTo(1);
context.close();
}

View File

@@ -55,18 +55,20 @@ public class ConfigServerConfigDataCustomizationIntegrationTests {
try {
BindHandlerBootstrapper bindHandlerBootstrapper = new BindHandlerBootstrapper();
context = new SpringApplicationBuilder(TestConfig.class)
.addBootstrapRegistryInitializer(bindHandlerBootstrapper)
.addBootstrapRegistryInitializer(ConfigServerBootstrapper.create()
.withLoaderInterceptor(new Interceptor()).withRestTemplateFactory(this::restTemplate))
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
BootstrapContext bootstrapContext = event.getBootstrapContext();
ConfigurableListableBeanFactory beanFactory = event.getApplicationContext().getBeanFactory();
.addBootstrapRegistryInitializer(bindHandlerBootstrapper)
.addBootstrapRegistryInitializer(ConfigServerBootstrapper.create()
.withLoaderInterceptor(new Interceptor())
.withRestTemplateFactory(this::restTemplate))
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
BootstrapContext bootstrapContext = event.getBootstrapContext();
ConfigurableListableBeanFactory beanFactory = event.getApplicationContext().getBeanFactory();
RestTemplate restTemplate = bootstrapContext.get(RestTemplate.class);
beanFactory.registerSingleton("holder", new RestTemplateHolder(restTemplate));
beanFactory.registerSingleton("interceptor", bootstrapContext.get(LoaderInterceptor.class));
})).run("--spring.config.import=optional:configserver:", "--custom.prop=customval",
"--spring.cloud.config.label=mylabel");
RestTemplate restTemplate = bootstrapContext.get(RestTemplate.class);
beanFactory.registerSingleton("holder", new RestTemplateHolder(restTemplate));
beanFactory.registerSingleton("interceptor", bootstrapContext.get(LoaderInterceptor.class));
}))
.run("--spring.config.import=optional:configserver:", "--custom.prop=customval",
"--spring.cloud.config.label=mylabel");
RestTemplateHolder holder = context.getBean(RestTemplateHolder.class);
assertThat(holder).isNotNull();
@@ -118,8 +120,10 @@ public class ConfigServerConfigDataCustomizationIntegrationTests {
PropertySource<?> propertySource = configData.getPropertySources().iterator().next();
Options options = configData.getOptions(propertySource);
assertThat(options).as("ConfigData.options was null for location %s property source %s",
context.getResource(), propertySource.getName()).isNotNull();
assertThat(options)
.as("ConfigData.options was null for location %s property source %s", context.getResource(),
propertySource.getName())
.isNotNull();
assertThat(options.contains(Option.IGNORE_IMPORTS)).isTrue();
assertThat(options.contains(Option.PROFILE_SPECIFIC)).isFalse();
}

View File

@@ -130,7 +130,7 @@ public class ConfigServerConfigDataLoaderTests {
when(context.getBootstrapContext()).thenReturn(bootstrapContext);
when(bootstrapContext.get(ConfigClientRequestTemplateFactory.class))
.thenReturn(mock(ConfigClientRequestTemplateFactory.class));
.thenReturn(mock(ConfigClientRequestTemplateFactory.class));
when(bootstrapContext.get(RestTemplate.class)).thenReturn(restTemplate);
when(resource.getProperties()).thenReturn(properties);
@@ -147,8 +147,9 @@ public class ConfigServerConfigDataLoaderTests {
assertThat(this.loader.load(context, resource)).isNotNull();
Mockito.verify(this.restTemplate).exchange(anyString(), any(HttpMethod.class),
httpEntityArgumentCaptor.capture(), any(Class.class), anyString(), anyString());
Mockito.verify(this.restTemplate)
.exchange(anyString(), any(HttpMethod.class), httpEntityArgumentCaptor.capture(), any(Class.class),
anyString(), anyString());
HttpEntity<Void> httpEntity = httpEntityArgumentCaptor.getValue();
assertThat(httpEntity.getHeaders().getAccept()).containsExactly(MediaType.parseMediaType(V2_JSON));
@@ -163,9 +164,9 @@ public class ConfigServerConfigDataLoaderTests {
assertThat(loader.load(context, resource)).isNotNull();
Mockito.verify(this.restTemplate).exchange(anyString(), any(HttpMethod.class),
httpEntityArgumentCaptor.capture(), ArgumentMatchers.<Class<Environment>>any(), anyString(),
anyString());
Mockito.verify(this.restTemplate)
.exchange(anyString(), any(HttpMethod.class), httpEntityArgumentCaptor.capture(),
ArgumentMatchers.<Class<Environment>>any(), anyString(), anyString());
HttpEntity<Void> httpEntity = httpEntityArgumentCaptor.getValue();
assertThat(httpEntity.getHeaders().getAccept()).containsExactly(MediaType.parseMediaType("application/json"));
@@ -240,7 +241,7 @@ public class ConfigServerConfigDataLoaderTests {
IllegalStateException exception = Assertions.assertThrows(IllegalStateException.class,
() -> this.loader.load(context, resource));
assertThat(exception.getMessage())
.contains("Could not locate PropertySource and the fail fast property is set, failing");
.contains("Could not locate PropertySource and the fail fast property is set, failing");
}
@Test
@@ -404,11 +405,11 @@ public class ConfigServerConfigDataLoaderTests {
ConfigData configData = setupConfigServerConfigDataLoader(Arrays.asList(p1, p2), "application-slash", null);
assertThat(configData.getPropertySources()).hasSize(3);
assertThat(configData.getOptions(configData.getPropertySources().get(0))
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
assertThat(configData.getOptions(configData.getPropertySources().get(1))
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
assertThat(configData.getOptions(configData.getPropertySources().get(2))
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
}
@@ -457,9 +458,9 @@ public class ConfigServerConfigDataLoaderTests {
ConfigData configData = setupConfigServerConfigDataLoader(propertySources, "application-slash", "dev");
assertThat(configData.getPropertySources()).hasSize(2);
assertThat(configData.getOptions(configData.getPropertySources().get(0))
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
assertThat(configData.getOptions(configData.getPropertySources().get(1))
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
.contains(ConfigData.Option.IGNORE_IMPORTS)).isTrue();
}
@@ -530,19 +531,19 @@ public class ConfigServerConfigDataLoaderTests {
"application-slash", "def");
assertThat(configData.getPropertySources()).hasSize(7);
assertThat(configData.getOptions(configData.getPropertySources().get(0))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
assertThat(configData.getOptions(configData.getPropertySources().get(1))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isTrue();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isTrue();
assertThat(configData.getOptions(configData.getPropertySources().get(2))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
assertThat(configData.getOptions(configData.getPropertySources().get(3))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
assertThat(configData.getOptions(configData.getPropertySources().get(4))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
assertThat(configData.getOptions(configData.getPropertySources().get(5))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
assertThat(configData.getOptions(configData.getPropertySources().get(6))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isTrue();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isTrue();
}
@Test
@@ -559,15 +560,15 @@ public class ConfigServerConfigDataLoaderTests {
"default");
assertThat(configData.getPropertySources()).hasSize(5);
assertThat(configData.getOptions(configData.getPropertySources().get(0))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
assertThat(configData.getOptions(configData.getPropertySources().get(1))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isTrue();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isTrue();
assertThat(configData.getOptions(configData.getPropertySources().get(2))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
assertThat(configData.getOptions(configData.getPropertySources().get(3))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
assertThat(configData.getOptions(configData.getPropertySources().get(4))
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
.contains(ConfigData.Option.PROFILE_SPECIFIC)).isFalse();
}
private ConfigData setupConfigServerConfigDataLoader(List<PropertySource> propertySources, String applicationName,
@@ -580,11 +581,12 @@ public class ConfigServerConfigDataLoaderTests {
when(responseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
when(responseEntity.getBody()).thenReturn(environment);
when(rest.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), eq(Environment.class),
eq(applicationName), ArgumentMatchers.<String>any())).thenReturn(responseEntity);
eq(applicationName), ArgumentMatchers.<String>any()))
.thenReturn(responseEntity);
ConfigurableBootstrapContext bootstrapContext = mock(ConfigurableBootstrapContext.class);
when(bootstrapContext.get(eq(ConfigClientRequestTemplateFactory.class)))
.thenReturn(mock(ConfigClientRequestTemplateFactory.class));
.thenReturn(mock(ConfigClientRequestTemplateFactory.class));
when(bootstrapContext.get(eq(RestTemplate.class))).thenReturn(rest);
ConfigServerConfigDataLoader loader = new ConfigServerConfigDataLoader(destination -> mock(Log.class));
@@ -595,7 +597,7 @@ public class ConfigServerConfigDataLoaderTests {
properties.setName(applicationName);
Profiles profiles = mock(Profiles.class);
when(profiles.getAccepted())
.thenReturn(profileList == null ? Collections.singletonList("default") : Arrays.asList(profileList));
.thenReturn(profileList == null ? Collections.singletonList("default") : Arrays.asList(profileList));
ConfigServerConfigDataResource resource = new ConfigServerConfigDataResource(properties, false, profiles);
resource.setProfileSpecific(!ObjectUtils.isEmpty(profileList));
@@ -708,7 +710,8 @@ public class ConfigServerConfigDataLoaderTests {
}
else {
when(requestFactory.createRequest(eq(new URI(format(URI_TEMPLATE, baseURI, NAME, PROFILES, LABEL))),
any(HttpMethod.class))).thenReturn(request);
any(HttpMethod.class)))
.thenReturn(request);
}
when(request.getHeaders()).thenReturn(new HttpHeaders());
@@ -725,19 +728,22 @@ public class ConfigServerConfigDataLoaderTests {
@SuppressWarnings("unchecked")
private void mockRequestResponseWithLabel(ResponseEntity<?> response, String label) {
when(this.restTemplate.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class),
any(Class.class), anyString(), anyString(), eq(label))).thenReturn(response);
any(Class.class), anyString(), anyString(), eq(label)))
.thenReturn(response);
}
@SuppressWarnings("unchecked")
private void mockRequestResponseWithoutLabel(ResponseEntity<?> response) {
when(this.restTemplate.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class),
any(Class.class), anyString(), anyString())).thenReturn(response);
any(Class.class), anyString(), anyString()))
.thenReturn(response);
}
@SuppressWarnings("unchecked")
private void mockRequestTimedOut() {
when(this.restTemplate.exchange(any(String.class), any(HttpMethod.class), any(HttpEntity.class),
any(Class.class), anyString(), anyString(), anyString())).thenThrow(ResourceAccessException.class);
any(Class.class), anyString(), anyString(), anyString()))
.thenThrow(ResourceAccessException.class);
}
private void mockRequestTimedOut(ClientHttpRequestFactory requestFactory, String baseURI) throws Exception {
@@ -748,7 +754,8 @@ public class ConfigServerConfigDataLoaderTests {
}
else {
when(requestFactory.createRequest(eq(new URI(format(URI_TEMPLATE, baseURI, NAME, PROFILES, LABEL))),
any(HttpMethod.class))).thenReturn(request);
any(HttpMethod.class)))
.thenReturn(request);
}
when(request.getHeaders()).thenReturn(new HttpHeaders());

View File

@@ -252,9 +252,9 @@ public class ConfigServerConfigDataLocationResolverTests {
// Use this TextEncryptor in the BindHandler we return so it will decrypt the
// password when we bind ConfigClientProperties
TextEncryptor bindHandlerTextEncryptor = new EncryptorFactory(keyProperties.getSalt())
.create(keyProperties.getKey());
.create(keyProperties.getKey());
when(context.getBootstrapContext().getOrElse(eq(BindHandler.class), eq(null)))
.thenReturn(new TextEncryptorBindHandler(bindHandlerTextEncryptor, keyProperties));
.thenReturn(new TextEncryptorBindHandler(bindHandlerTextEncryptor, keyProperties));
// Call resolve so we can test that the delegate is added to the
// FailsafeTextEncryptor
@@ -265,12 +265,12 @@ public class ConfigServerConfigDataLocationResolverTests {
// ConfigServerConfigDataLocationResolver.resolveProfileSpecific
// it should have the decrypted passord in it
ArgumentCaptor<BootstrapRegistry.InstanceSupplier<ConfigClientProperties>> captor = ArgumentCaptor
.forClass(BootstrapRegistry.InstanceSupplier.class);
.forClass(BootstrapRegistry.InstanceSupplier.class);
verify(bootstrapContext).register(eq(ConfigClientProperties.class), captor.capture());
assertThat(captor.getValue().get(bootstrapContext).getPassword()).isEqualTo("password");
assertThat(textEncryptor).isInstanceOf(TextEncryptorUtils.FailsafeTextEncryptor.class);
assertThat(((TextEncryptorUtils.FailsafeTextEncryptor) textEncryptor).getDelegate())
.isInstanceOf(TextEncryptor.class);
.isInstanceOf(TextEncryptor.class);
}
private ConfigServerConfigDataResource testUri(String propertyUri, String locationUri) {

View File

@@ -36,7 +36,7 @@ class ConfigServerConfigDataMissingEnvironmentPostProcessorTests {
SpringApplication app = mock(SpringApplication.class);
ConfigServerConfigDataMissingEnvironmentPostProcessor processor = new ConfigServerConfigDataMissingEnvironmentPostProcessor();
assertThatThrownBy(() -> processor.postProcessEnvironment(environment, app))
.isInstanceOf(ConfigServerConfigDataMissingEnvironmentPostProcessor.ImportException.class);
.isInstanceOf(ConfigServerConfigDataMissingEnvironmentPostProcessor.ImportException.class);
}
@Test

View File

@@ -43,31 +43,29 @@ public class ConfigServerConfigDataNoImportIntegrationTests {
@Test
public void exceptionThrownIfNoImport(CapturedOutput output) {
Assertions
.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
assertThat(output).contains("No spring.config.import property has been defined")
.contains("Add a spring.config.import=configserver: property to your configuration");
.contains("Add a spring.config.import=configserver: property to your configuration");
}
@Test
public void exceptionThrownIfImportMissing(CapturedOutput output) {
Assertions
.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run(
"--spring.config.import=optional:file:somefile.properties",
"--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
Assertions.assertThatThrownBy(() -> new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE)
.run("--spring.config.import=optional:file:somefile.properties", "--spring.application.name=" + APP_NAME))
.isInstanceOf(ConfigDataMissingEnvironmentPostProcessor.ImportException.class);
assertThat(output).contains("spring.config.import property is missing a " + PREFIX)
.contains("Add a spring.config.import=configserver: property to your configuration");
.contains("Add a spring.config.import=configserver: property to your configuration");
}
@Test
public void noExceptionThrownIfConfigDisabled() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE)
.run("--spring.cloud.config.enabled=false", "--spring.application.name=" + APP_NAME)) {
.web(WebApplicationType.NONE)
.run("--spring.cloud.config.enabled=false", "--spring.application.name=" + APP_NAME)) {
// nothing to do
}
}
@@ -75,8 +73,8 @@ public class ConfigServerConfigDataNoImportIntegrationTests {
@Test
public void noExceptionThrownIfImportCheckDisabled() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(Config.class)
.web(WebApplicationType.NONE)
.run("--spring.cloud.config.import-check.enabled=false", "--spring.application.name=" + APP_NAME)) {
.web(WebApplicationType.NONE)
.run("--spring.cloud.config.import-check.enabled=false", "--spring.application.name=" + APP_NAME)) {
// nothing to do
}
}

View File

@@ -150,7 +150,7 @@ class ConfigServerConfigDataResourceTests {
r1Properties.setUri(new String[] { "http://localhost:8888", "http://localhost:9999", "http://localhost:7777" });
ConfigClientProperties r2Properties = new ConfigClientProperties();
r2Properties
.setUri(new String[] { "https://localhost:7777", "https://localhost:8888", "https://localhost:9999" });
.setUri(new String[] { "https://localhost:7777", "https://localhost:8888", "https://localhost:9999" });
ConfigServerConfigDataResource r1 = new ConfigServerConfigDataResource(r1Properties, true,
mock(Profiles.class));
ConfigServerConfigDataResource r2 = new ConfigServerConfigDataResource(r2Properties, true,

View File

@@ -55,7 +55,7 @@ public class ConfigServiceBootstrapConfigurationRetryTest {
@Test
public void exponentialBackoffPolicy() {
TestPropertyValues.of("spring.cloud.config.enabled=true", "spring.cloud.config.fail-fast=true")
.applyTo(this.context);
.applyTo(this.context);
this.context.register(ConfigServiceBootstrapConfiguration.class);
this.context.refresh();
@@ -75,8 +75,10 @@ public class ConfigServiceBootstrapConfigurationRetryTest {
@Test
public void exponentialRandomBackoffPolicy() {
TestPropertyValues.of("spring.cloud.config.enabled=true", "spring.cloud.config.fail-fast=true",
"spring.cloud.config.retry.useRandomPolicy=true").applyTo(this.context);
TestPropertyValues
.of("spring.cloud.config.enabled=true", "spring.cloud.config.fail-fast=true",
"spring.cloud.config.retry.useRandomPolicy=true")
.applyTo(this.context);
this.context.register(ConfigServiceBootstrapConfiguration.class);
this.context.refresh();

View File

@@ -82,8 +82,9 @@ public class ConfigServicePropertySourceLocatorTests {
assertThat(this.locator.locateCollection(this.environment)).isNotNull();
Mockito.verify(this.restTemplate).exchange(anyString(), any(HttpMethod.class), argumentCaptor.capture(),
any(Class.class), anyString(), anyString());
Mockito.verify(this.restTemplate)
.exchange(anyString(), any(HttpMethod.class), argumentCaptor.capture(), any(Class.class), anyString(),
anyString());
HttpEntity httpEntity = argumentCaptor.getValue();
assertThat(httpEntity.getHeaders().getAccept()).containsExactly(MediaType.parseMediaType(V2_JSON));
@@ -102,8 +103,9 @@ public class ConfigServicePropertySourceLocatorTests {
assertThat(locator.locateCollection(this.environment)).isNotNull();
Mockito.verify(this.restTemplate).exchange(anyString(), any(HttpMethod.class), argumentCaptor.capture(),
any(Class.class), anyString(), anyString());
Mockito.verify(this.restTemplate)
.exchange(anyString(), any(HttpMethod.class), argumentCaptor.capture(), any(Class.class), anyString(),
anyString());
HttpEntity httpEntity = argumentCaptor.getValue();
assertThat(httpEntity.getHeaders().getAccept()).containsExactly(MediaType.parseMediaType("application/json"));
@@ -125,7 +127,7 @@ public class ConfigServicePropertySourceLocatorTests {
mockRequestResponseWithProfile(new ResponseEntity<>(body, HttpStatus.OK), "override-profile");
this.locator.setRestTemplate(this.restTemplate);
TestPropertyValues.of("spring.cloud.config.profile:override-profile", "spring.profiles.active: foo")
.applyTo(this.environment);
.applyTo(this.environment);
assertThat(this.locator.locateCollection(this.environment).size()).isEqualTo(2);
}
@@ -155,8 +157,10 @@ public class ConfigServicePropertySourceLocatorTests {
this.locator.setRestTemplate(this.restTemplate);
TestPropertyValues.of("spring.cloud.config.label:release/v1.0.1").applyTo(this.environment);
this.locator.locateCollection(this.environment);
}).isInstanceOf(IllegalStateException.class).hasMessageContaining(
"Could not locate PropertySource and the fail fast property is set, failing: None of labels [release/v1.0.1] found");
})
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining(
"Could not locate PropertySource and the fail fast property is set, failing: None of labels [release/v1.0.1] found");
}
@Test
@@ -177,8 +181,10 @@ public class ConfigServicePropertySourceLocatorTests {
this.locator = new ConfigServicePropertySourceLocator(defaults);
this.locator.setRestTemplate(restTemplate);
this.locator.locateCollection(this.environment);
}).isInstanceOf(IllegalStateException.class).hasCauseInstanceOf(HttpServerErrorException.class)
.hasMessageContaining("fail fast property is set");
})
.isInstanceOf(IllegalStateException.class)
.hasCauseInstanceOf(HttpServerErrorException.class)
.hasMessageContaining("fail fast property is set");
}
@Test
@@ -192,8 +198,9 @@ public class ConfigServicePropertySourceLocatorTests {
this.locator = new ConfigServicePropertySourceLocator(defaults);
this.locator.setRestTemplate(restTemplate);
this.locator.locateCollection(this.environment);
}).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("fail fast property is set, failing: None of labels [] found");
})
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("fail fast property is set, failing: None of labels [] found");
}
@Test
@@ -214,7 +221,7 @@ public class ConfigServicePropertySourceLocatorTests {
ClientHttpRequestFactory requestFactory = Mockito.mock(ClientHttpRequestFactory.class);
ClientHttpRequest request = Mockito.mock(ClientHttpRequest.class);
Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class)))
.thenReturn(request);
.thenReturn(request);
ConfigClientProperties defaults = new ConfigClientProperties(this.environment);
defaults.setFailFast(true);
defaults.setUsername("username");
@@ -222,8 +229,9 @@ public class ConfigServicePropertySourceLocatorTests {
defaults.getHeaders().put(AUTHORIZATION, "Basic dXNlcm5hbWU6cGFzc3dvcmQNCg==");
this.locator = new ConfigServicePropertySourceLocator(defaults);
this.locator.locateCollection(this.environment);
}).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Could not locate PropertySource and the fail fast property is set, failing");
})
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Could not locate PropertySource and the fail fast property is set, failing");
}
@Test
@@ -268,8 +276,9 @@ public class ConfigServicePropertySourceLocatorTests {
String username = "user";
String password = "pass";
factory(defaults).addAuthorizationToken(headers, username, password);
}).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("You must set either 'password' or 'authorization'");
})
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("You must set either 'password' or 'authorization'");
}
@Test
@@ -396,7 +405,7 @@ public class ConfigServicePropertySourceLocatorTests {
Iterator<ClientHttpRequestInterceptor> iterator = restTemplate.getInterceptors().iterator();
while (iterator.hasNext()) {
GenericRequestHeaderInterceptor genericRequestHeaderInterceptor = (GenericRequestHeaderInterceptor) iterator
.next();
.next();
assertThat(genericRequestHeaderInterceptor.getHeaders()).doesNotContainKeys(AUTHORIZATION);
}
}
@@ -557,11 +566,13 @@ public class ConfigServicePropertySourceLocatorTests {
if (baseURI == null) {
Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class)))
.thenReturn(request);
.thenReturn(request);
}
else {
Mockito.when(requestFactory.createRequest(Mockito.eq(new URI(baseURI + "/application/default")),
Mockito.any(HttpMethod.class))).thenReturn(request);
Mockito
.when(requestFactory.createRequest(Mockito.eq(new URI(baseURI + "/application/default")),
Mockito.any(HttpMethod.class)))
.thenReturn(request);
}
Mockito.when(request.getHeaders()).thenReturn(new HttpHeaders());
@@ -579,27 +590,30 @@ public class ConfigServicePropertySourceLocatorTests {
private void mockRequestResponseWithLabel(ResponseEntity<?> response, String label) {
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class), Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class), Mockito.any(Class.class), anyString(), anyString(),
ArgumentMatchers.eq(label))).thenReturn(response);
ArgumentMatchers.eq(label)))
.thenReturn(response);
}
private void mockRequestResponseWithProfile(ResponseEntity<?> response, String profiles) {
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class), Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class), Mockito.any(Class.class), anyString(), ArgumentMatchers.eq(profiles)))
.thenReturn(response);
.thenReturn(response);
}
@SuppressWarnings("unchecked")
private void mockRequestResponseWithoutLabel(ResponseEntity<?> response) {
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class), Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class), Mockito.any(Class.class), anyString(), anyString()))
.thenReturn(response);
Mockito
.when(this.restTemplate.exchange(Mockito.any(String.class), Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class), Mockito.any(Class.class), anyString(), anyString()))
.thenReturn(response);
}
@SuppressWarnings("unchecked")
private void mockRequestTimedOut() {
Mockito.when(this.restTemplate.exchange(Mockito.any(String.class), Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class), Mockito.any(Class.class), anyString(), anyString()))
.thenThrow(ResourceAccessException.class);
Mockito
.when(this.restTemplate.exchange(Mockito.any(String.class), Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class), Mockito.any(Class.class), anyString(), anyString()))
.thenThrow(ResourceAccessException.class);
}
private void mockRequestTimedOut(ClientHttpRequestFactory requestFactory, String baseURI) throws Exception {
@@ -607,11 +621,13 @@ public class ConfigServicePropertySourceLocatorTests {
if (baseURI == null) {
Mockito.when(requestFactory.createRequest(Mockito.any(URI.class), Mockito.any(HttpMethod.class)))
.thenReturn(request);
.thenReturn(request);
}
else {
Mockito.when(requestFactory.createRequest(Mockito.eq(new URI(baseURI + "/application/default")),
Mockito.any(HttpMethod.class))).thenReturn(request);
Mockito
.when(requestFactory.createRequest(Mockito.eq(new URI(baseURI + "/application/default")),
Mockito.any(HttpMethod.class)))
.thenReturn(request);
}
Mockito.when(request.getHeaders()).thenReturn(new HttpHeaders());

View File

@@ -75,10 +75,11 @@ public class DiscoveryClientConfigDataConfigurationNoRetryTests {
givenDiscoveryClientReturnsNoInfo();
ConfigServerInstanceProvider.Function function = mock(ConfigServerInstanceProvider.Function.class);
when(function.apply(anyString(), any(Binder.class), any(BindHandler.class), any(Log.class)))
.thenAnswer(invocation -> client.getInstances(invocation.getArgument(0)));
.thenAnswer(invocation -> client.getInstances(invocation.getArgument(0)));
assertThatThrownBy(() -> context = setup(true, function, "spring.cloud.config.discovery.enabled=true",
"spring.cloud.config.fail-fast=true").run()).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("No instances found of configserver");
"spring.cloud.config.fail-fast=true")
.run()).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("No instances found of configserver");
verify(function).apply(eq(DEFAULT_CONFIG_SERVER), any(Binder.class), any(BindHandler.class), any(Log.class));
verify(function, never()).apply(eq(DEFAULT_CONFIG_SERVER));
}
@@ -88,9 +89,10 @@ public class DiscoveryClientConfigDataConfigurationNoRetryTests {
givenDiscoveryClientReturnsNoInfo();
ConfigServerInstanceProvider.Function function = mock(ConfigServerInstanceProvider.Function.class);
when(function.apply(anyString(), any(Binder.class), any(BindHandler.class), any(Log.class)))
.thenAnswer(invocation -> client.getInstances(invocation.getArgument(0)));
.thenAnswer(invocation -> client.getInstances(invocation.getArgument(0)));
context = setup(true, function, "spring.cloud.config.discovery.enabled=true",
"spring.cloud.config.fail-fast=false").run();
"spring.cloud.config.fail-fast=false")
.run();
// expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
expectConfigClientPropertiesHasDefaultConfiguration();
@@ -104,9 +106,10 @@ public class DiscoveryClientConfigDataConfigurationNoRetryTests {
givenDiscoveryClientReturnsInfo();
ConfigServerInstanceProvider.Function function = mock(ConfigServerInstanceProvider.Function.class);
when(function.apply(eq(DEFAULT_CONFIG_SERVER), any(Binder.class), any(BindHandler.class), any(Log.class)))
.thenAnswer(invocation -> client.getInstances(invocation.getArgument(0)));
.thenAnswer(invocation -> client.getInstances(invocation.getArgument(0)));
context = setup(true, function, "spring.cloud.config.discovery.enabled=true",
"spring.cloud.config.fail-fast=true").run();
"spring.cloud.config.fail-fast=true")
.run();
// expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
// expectConfigClientPropertiesHasConfigurationFromEureka();
@@ -118,13 +121,13 @@ public class DiscoveryClientConfigDataConfigurationNoRetryTests {
SpringApplicationBuilder setup(boolean addInstanceProvider, ConfigServerInstanceProvider.Function function,
String... env) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(TestConfig.class)
.properties(addDefaultEnv(env));
.properties(addDefaultEnv(env));
if (addInstanceProvider) {
builder.addBootstrapRegistryInitializer(instanceProviderBootstrapper(function));
// ignore actual calls to config server since we're just testing discovery
// client.
builder.addBootstrapRegistryInitializer(registry -> registry
.register(ConfigServerBootstrapper.LoaderInterceptor.class, ctx -> loadContext -> null));
.register(ConfigServerBootstrapper.LoaderInterceptor.class, ctx -> loadContext -> null));
}
return builder.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
ConfigServerInstanceMonitor monitor = event.getBootstrapContext().get(ConfigServerInstanceMonitor.class);

View File

@@ -66,16 +66,17 @@ public class DiscoveryClientConfigDataConfigurationTests {
@Test
public void offByDefault() {
context = new SpringApplicationBuilder(TestConfig.class)
.properties("spring.config.import=optional:configserver:")
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
try {
event.getBootstrapContext().get(ConfigServerInstanceMonitor.class);
fail("ConfigServerInstanceMonitor was created when it shouldn't");
}
catch (IllegalStateException e) {
// expected
}
})).run();
.properties("spring.config.import=optional:configserver:")
.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
try {
event.getBootstrapContext().get(ConfigServerInstanceMonitor.class);
fail("ConfigServerInstanceMonitor was created when it shouldn't");
}
catch (IllegalStateException e) {
// expected
}
}))
.run();
}
@Test
@@ -169,7 +170,8 @@ public class DiscoveryClientConfigDataConfigurationTests {
givenDiscoveryClientReturnsInfoOnThirdTry();
context = setup("spring.cloud.config.retry.maxAttempts=3", "spring.cloud.config.retry.initialInterval=10",
"spring.cloud.config.fail-fast=true").run();
"spring.cloud.config.fail-fast=true")
.run();
verifyDiscoveryClientCalledThreeTimes();
@@ -183,7 +185,7 @@ public class DiscoveryClientConfigDataConfigurationTests {
givenDiscoveryClientReturnsInfoOnThirdTry();
context = setup("spring.cloud.config.retry.maxAttempts=3", "spring.cloud.config.retry.initialInterval=10")
.run();
.run();
verifyDiscoveryClientCalledOnce();
expectConfigClientPropertiesHasDefaultConfiguration();
@@ -194,9 +196,9 @@ public class DiscoveryClientConfigDataConfigurationTests {
givenDiscoveryClientReturnsNoInfo();
assertThatThrownBy(() -> context = setup("spring.cloud.config.retry.maxAttempts=3",
"spring.cloud.config.retry.initialInterval=10", "spring.cloud.config.fail-fast=true").run())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("No instances found of configserver");
"spring.cloud.config.retry.initialInterval=10", "spring.cloud.config.fail-fast=true")
.run()).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("No instances found of configserver");
}
@Test
@@ -204,7 +206,8 @@ public class DiscoveryClientConfigDataConfigurationTests {
givenDiscoveryClientReturnsNoInfo();
context = setup("spring.cloud.config.retry.maxAttempts=3", "spring.cloud.config.retry.initialInterval=10",
"spring.cloud.config.fail-fast=false").run();
"spring.cloud.config.fail-fast=false")
.run();
expectConfigClientPropertiesHasDefaultConfiguration();
}
@@ -215,13 +218,13 @@ public class DiscoveryClientConfigDataConfigurationTests {
SpringApplicationBuilder setup(boolean addInstanceProvider, String... env) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(TestConfig.class)
.properties(addDefaultEnv(env));
.properties(addDefaultEnv(env));
if (addInstanceProvider) {
builder.addBootstrapRegistryInitializer(instanceProviderBootstrapper());
// ignore actual calls to config server since we're just testing discovery
// client.
builder.addBootstrapRegistryInitializer(registry -> registry
.register(ConfigServerBootstrapper.LoaderInterceptor.class, ctx -> loadContext -> null));
.register(ConfigServerBootstrapper.LoaderInterceptor.class, ctx -> loadContext -> null));
}
return builder.addBootstrapRegistryInitializer(registry -> registry.addCloseListener(event -> {
ConfigServerInstanceMonitor monitor = event.getBootstrapContext().get(ConfigServerInstanceMonitor.class);
@@ -262,7 +265,8 @@ public class DiscoveryClientConfigDataConfigurationTests {
void givenDiscoveryClientReturnsInfoOnThirdTry() {
given(this.client.getInstances(DEFAULT_CONFIG_SERVER)).willReturn(Collections.emptyList())
.willReturn(Collections.emptyList()).willReturn(Collections.singletonList(this.info));
.willReturn(Collections.emptyList())
.willReturn(Collections.singletonList(this.info));
}
void verifyDiscoveryClientCalledOnce() {

View File

@@ -31,8 +31,9 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTest
org.assertj.core.api.Assertions.assertThatThrownBy(() -> {
givenDiscoveryClientReturnsNoInfo();
setup("spring.cloud.config.discovery.enabled=true", "spring.cloud.config.fail-fast=true");
}).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("No instances found of configserver (" + DEFAULT_CONFIG_SERVER + ")");
})
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("No instances found of configserver (" + DEFAULT_CONFIG_SERVER + ")");
}
@Test

View File

@@ -45,7 +45,7 @@ public class DiscoveryClientConfigServiceBootstrapConfigurationTests
assertThat(this.context.getBeanNamesForType(DiscoveryClient.class).length).isEqualTo(0);
assertThat(this.context.getBeanNamesForType(DiscoveryClientConfigServiceBootstrapConfiguration.class).length)
.isEqualTo(0);
.isEqualTo(0);
}
@Test

View File

@@ -85,7 +85,7 @@ public class PropertyPathEndpoint implements ApplicationEventPublisherAware {
for (String service : services) {
log.info("Refresh for: " + service);
this.applicationEventPublisher
.publishEvent(new RefreshRemoteApplicationEvent(this, this.busId, service));
.publishEvent(new RefreshRemoteApplicationEvent(this, this.busId, service));
}
return services;
}

View File

@@ -36,7 +36,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class CompositePropertyPathNotificationExtractorTests {
private CompositePropertyPathNotificationExtractor extractor = new CompositePropertyPathNotificationExtractor(Arrays
.asList(new GitlabPropertyPathNotificationExtractor(), new GithubPropertyPathNotificationExtractor()));
.asList(new GitlabPropertyPathNotificationExtractor(), new GithubPropertyPathNotificationExtractor()));
private HttpHeaders headers = new HttpHeaders();

View File

@@ -42,10 +42,13 @@ public class EnvironmentMonitorAutoConfigurationTests {
public void testExtractorsCount() {
ConfigurableApplicationContext context = new SpringApplicationBuilder(BusConfig.class,
EnvironmentMonitorAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class,
ServerProperties.class, PropertyPlaceholderAutoConfiguration.class).properties("server.port=-1").run();
ServerProperties.class, PropertyPlaceholderAutoConfiguration.class)
.properties("server.port=-1")
.run();
PropertyPathEndpoint endpoint = context.getBean(PropertyPathEndpoint.class);
assertThat(((Collection<?>) ReflectionTestUtils.getField(ReflectionTestUtils.getField(endpoint, "extractor"),
"extractors"))).hasSize(7);
"extractors")))
.hasSize(7);
context.close();
}
@@ -54,10 +57,13 @@ public class EnvironmentMonitorAutoConfigurationTests {
ConfigurableApplicationContext context = new SpringApplicationBuilder(BusConfig.class,
CustomPropertyPathNotificationExtractorConfig.class, EnvironmentMonitorAutoConfiguration.class,
ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class,
PropertyPlaceholderAutoConfiguration.class).properties("server.port=-1").run();
PropertyPlaceholderAutoConfiguration.class)
.properties("server.port=-1")
.run();
PropertyPathEndpoint endpoint = context.getBean(PropertyPathEndpoint.class);
assertThat(((Collection<?>) ReflectionTestUtils.getField(ReflectionTestUtils.getField(endpoint, "extractor"),
"extractors"))).hasSize(8);
"extractors")))
.hasSize(8);
context.close();
}

View File

@@ -65,40 +65,42 @@ public class PropertyPathEndpointTests {
@Test
public void testNotifyAll() {
assertThat(this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "application.yml"))
.toString()).isEqualTo("[*]");
.toString()).isEqualTo("[*]");
}
@Test
public void testNotifyAllWithProfile() {
assertThat(this.endpoint
.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "application-local.yml")).toString())
.isEqualTo("[application-local, *]");
assertThat(
this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "application-local.yml"))
.toString())
.isEqualTo("[application-local, *]");
}
@Test
public void testNotifyOne() {
assertThat(
this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "foo.yml")).toString())
.isEqualTo("[foo]");
.isEqualTo("[foo]");
}
@Test
public void testNotifyOneWithWindowsPath() {
assertThat(this.endpoint
.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "C:\\config\\foo.yml")).toString())
.isEqualTo("[foo]");
assertThat(
this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "C:\\config\\foo.yml"))
.toString())
.isEqualTo("[foo]");
}
@Test
public void testNotifyOneWithProfile() {
assertThat(this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "foo-local.yml"))
.toString()).isEqualTo("[foo-local, foo]");
.toString()).isEqualTo("[foo-local, foo]");
}
@Test
public void testNotifyMultiDash() {
assertThat(this.endpoint.notifyByPath(new HttpHeaders(), Collections.singletonMap("path", "foo-local-dev.yml"))
.toString()).isEqualTo("[foo-local-dev, foo-local, foo]");
.toString()).isEqualTo("[foo-local-dev, foo-local, foo]");
}
}

View File

@@ -34,21 +34,22 @@ public class ApplicationFailFastTests {
@Test
public void bootstrapContextFails() {
assertThatThrownBy(() -> {
new SpringApplicationBuilder().sources(Application.class).run("--spring.config.use-legacy-processing=true",
"--server.port=0", "--spring.cloud.config.enabled=true", "--spring.cloud.config.fail-fast=true",
"--spring.cloud.config.uri=http://serverhostdoesnotexist:1234");
new SpringApplicationBuilder().sources(Application.class)
.run("--spring.config.use-legacy-processing=true", "--server.port=0",
"--spring.cloud.config.enabled=true", "--spring.cloud.config.fail-fast=true",
"--spring.cloud.config.uri=http://serverhostdoesnotexist:1234");
}).as("Exception not caused by fail fast").hasMessageContaining("fail fast");
}
@Test
public void configDataContextFailsFast(CapturedOutput output) {
assertThatThrownBy(() -> {
new SpringApplicationBuilder().sources(Application.class, PropertyInjectionConfiguration.class).run(
"--server.port=0", "--spring.cloud.config.enabled=true", "--spring.cloud.config.fail-fast=true",
"--spring.config.import=optional:configserver:http://serverhostdoesnotexist:1234",
"--spring.cloud.config.server.enabled=false", "--logging.level.org.springframework.retry=TRACE",
"--logging.level.org.springframework.cloud.config=TRACE",
"--logging.level.org.springframework.boot.context.config=TRACE");
new SpringApplicationBuilder().sources(Application.class, PropertyInjectionConfiguration.class)
.run("--server.port=0", "--spring.cloud.config.enabled=true", "--spring.cloud.config.fail-fast=true",
"--spring.config.import=optional:configserver:http://serverhostdoesnotexist:1234",
"--spring.cloud.config.server.enabled=false", "--logging.level.org.springframework.retry=TRACE",
"--logging.level.org.springframework.cloud.config=TRACE",
"--logging.level.org.springframework.boot.context.config=TRACE");
}).as("Exception not caused by fail fast").hasMessageContaining("fail fast");
assertThat(output).contains("Retry: count=5").doesNotContain("Could not resolve placeholder");
}

View File

@@ -82,15 +82,17 @@ public class ConfigDataCustomMediaTypeIntegrationTests {
@SuppressWarnings("unchecked")
public void noOriginWithMediaTypeApplicationJson() {
MutablePropertySources sources = env.getPropertySources();
sources.stream().filter(propertySource -> propertySource.getName().startsWith("configserver:")).findFirst()
.ifPresent(propertySource -> {
if (propertySource instanceof OriginLookup) {
OriginLookup<String> originLookup = (OriginLookup) propertySource;
Origin origin = originLookup.getOrigin("info.foo");
// because media-type was set as application/json, no origin
assertThat(origin).as("origin was not null").isNull();
}
});
sources.stream()
.filter(propertySource -> propertySource.getName().startsWith("configserver:"))
.findFirst()
.ifPresent(propertySource -> {
if (propertySource instanceof OriginLookup) {
OriginLookup<String> originLookup = (OriginLookup) propertySource;
Origin origin = originLookup.getOrigin("info.foo");
// because media-type was set as application/json, no origin
assertThat(origin).as("origin was not null").isNull();
}
});
assertThat(env.getProperty("info.foo")).isEqualTo("bar");
}

View File

@@ -75,7 +75,7 @@ public class ConfigDataOrderingIntegrationTests {
@SuppressWarnings({ "unchecked", "rawtypes" })
public void contextLoads() {
ResponseEntity<Map> response = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port + BASE_PATH + "/env/my.prop", Map.class);
.getForEntity("http://localhost:" + this.port + BASE_PATH + "/env/my.prop", Map.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
Map res = response.getBody();
assertThat(res).containsKey("propertySources");

View File

@@ -54,8 +54,9 @@ public class ConfigDataOrderingVaultIntegrationTests {
@Container
public static VaultContainer vaultContainer = new VaultContainer<>(DockerImageName.parse("vault:1.13.3"))
.withVaultToken("my-root-token").withClasspathResourceMapping("vaultordering/vault_test_policy.txt",
"/tmp/vault_test_policy.txt", BindMode.READ_ONLY);
.withVaultToken("my-root-token")
.withClasspathResourceMapping("vaultordering/vault_test_policy.txt", "/tmp/vault_test_policy.txt",
BindMode.READ_ONLY);
@BeforeAll
public static void startConfigServer() throws IOException, InterruptedException, JSONException {

View File

@@ -34,7 +34,7 @@ public class ConfigServerApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ConfigServerApplication.class).properties("spring.config.name=configserver")
.run(args);
.run(args);
}
}

View File

@@ -79,16 +79,19 @@ public class CompositeEnvironmentBeanFactoryInitializationAotProcessor
private static Map<String, BeanDefinition> getCompositeEnvironmentBeanDefinitions(
ConfigurableListableBeanFactory beanFactory, String infix, Class<?> beanClass) {
return Arrays.stream(beanFactory.getBeanDefinitionNames()).filter(beanName -> beanName.contains(infix))
.map(beanName -> Map.entry(beanName, beanFactory.getBeanDefinition(beanName))).filter(entry -> {
try {
return beanClass.isAssignableFrom(Class.forName(entry.getValue().getBeanClassName()));
}
catch (ClassNotFoundException e) {
throw new RuntimeException(
"Class " + entry.getValue().getBeanClassName() + " could not be found", e);
}
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return Arrays.stream(beanFactory.getBeanDefinitionNames())
.filter(beanName -> beanName.contains(infix))
.map(beanName -> Map.entry(beanName, beanFactory.getBeanDefinition(beanName)))
.filter(entry -> {
try {
return beanClass.isAssignableFrom(Class.forName(entry.getValue().getBeanClassName()));
}
catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + entry.getValue().getBeanClassName() + " could not be found",
e);
}
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
@Override
@@ -123,10 +126,10 @@ public class CompositeEnvironmentBeanFactoryInitializationAotProcessor
public void applyTo(GenerationContext generationContext,
BeanFactoryInitializationCode beanFactoryInitializationCode) {
GeneratedMethod environmentRepositoryPropertiesGeneratedMethod = beanFactoryInitializationCode.getMethods()
.add("registerCompositeEnvironmentRepositoryPropertiesBeanDefinitions",
this::generateRegisterBeanDefinitionsMethod);
.add("registerCompositeEnvironmentRepositoryPropertiesBeanDefinitions",
this::generateRegisterBeanDefinitionsMethod);
beanFactoryInitializationCode
.addInitializer(environmentRepositoryPropertiesGeneratedMethod.toMethodReference());
.addInitializer(environmentRepositoryPropertiesGeneratedMethod.toMethodReference());
generateRuntimeHints(generationContext.getRuntimeHints());
}
@@ -154,16 +157,16 @@ public class CompositeEnvironmentBeanFactoryInitializationAotProcessor
String repoBeanName = beanName.replace("repo-properties", "repo");
String factoryName = repoBeanDefinitions.get(repoBeanName).getFactoryBeanName();
Class<? extends EnvironmentRepositoryFactory<? extends EnvironmentRepository, ? extends EnvironmentRepositoryProperties>> factoryClass = (Class<? extends EnvironmentRepositoryFactory<? extends EnvironmentRepository, ? extends EnvironmentRepositoryProperties>>) CompositeUtils
.getFactoryClass(beanFactory, factoryName);
.getFactoryClass(beanFactory, factoryName);
Type[] environmentRepositoryFactoryTypeParams = CompositeUtils
.getEnvironmentRepositoryFactoryTypeParams(factoryClass);
.getEnvironmentRepositoryFactoryTypeParams(factoryClass);
Class<? extends EnvironmentRepositoryProperties> repoClass = (Class<? extends EnvironmentRepositoryProperties>) environmentRepositoryFactoryTypeParams[0];
Class<? extends EnvironmentRepositoryProperties> propertiesClass = (Class<? extends EnvironmentRepositoryProperties>) environmentRepositoryFactoryTypeParams[1];
hintClasses.addAll(Set.of(repoClass, propertiesClass, factoryClass));
String indexString = matcher.group(3);
int index = Integer.parseInt(indexString);
String environmentConfigurationPropertyName = String
.format("spring.cloud.config.server.composite[%d]", index);
.format("spring.cloud.config.server.composite[%d]", index);
method.addStatement("$T properties$L = binder.bindOrCreate($S, $T.class)",
EnvironmentRepositoryProperties.class, index, environmentConfigurationPropertyName,
propertiesClass);

View File

@@ -60,13 +60,16 @@ public class CompositeEnvironmentBeanFactoryPostProcessor implements BeanFactory
propertiesClass = (Class<? extends EnvironmentRepositoryProperties>) factoryTypes[1];
EnvironmentRepositoryProperties properties = bindProperties(i, propertiesClass, this.environment);
AbstractBeanDefinition propertiesDefinition = BeanDefinitionBuilder
.genericBeanDefinition(EnvironmentRepositoryProperties.class, () -> properties).getBeanDefinition();
.genericBeanDefinition(EnvironmentRepositoryProperties.class, () -> properties)
.getBeanDefinition();
String propertiesBeanName = String.format("%s-env-repo-properties%d", type, i);
registry.registerBeanDefinition(propertiesBeanName, propertiesDefinition);
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
.genericBeanDefinition(EnvironmentRepository.class).setFactoryMethodOnBean("build", factoryName)
.addConstructorArgValue(properties).getBeanDefinition();
.genericBeanDefinition(EnvironmentRepository.class)
.setFactoryMethodOnBean("build", factoryName)
.addConstructorArgValue(properties)
.getBeanDefinition();
String beanName = String.format("%s-env-repo%d", type, i);
registry.registerBeanDefinition(beanName, beanDefinition);
}

View File

@@ -51,8 +51,13 @@ public final class CompositeUtils {
* @return list of matching types
*/
public static List<String> getCompositeTypeList(Environment environment) {
return Binder.get(environment).bind("spring.cloud.config.server", CompositeConfig.class).get().getComposite()
.stream().map(map -> (String) map.get("type")).collect(Collectors.toList());
return Binder.get(environment)
.bind("spring.cloud.config.server", CompositeConfig.class)
.get()
.getComposite()
.stream()
.map(map -> (String) map.get("type"))
.collect(Collectors.toList());
}
/**
@@ -65,8 +70,10 @@ public final class CompositeUtils {
public static String getFactoryName(String type, ConfigurableListableBeanFactory beanFactory) {
String[] factoryNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory,
EnvironmentRepositoryFactory.class, true, false);
return Arrays.stream(factoryNames).filter(n -> StringUtils.startsWithIgnoreCase(n, type)).findFirst()
.orElse(null);
return Arrays.stream(factoryNames)
.filter(n -> StringUtils.startsWithIgnoreCase(n, type))
.findFirst()
.orElse(null);
}
/**
@@ -90,12 +97,14 @@ public final class CompositeUtils {
*/
public static Type[] getEnvironmentRepositoryFactoryTypeParams(Class<?> factoryClass) {
Optional<AnnotatedType> annotatedFactoryType = Arrays.stream(factoryClass.getAnnotatedInterfaces())
.filter(i -> {
ParameterizedType parameterizedType = (ParameterizedType) i.getType();
return parameterizedType.getRawType().equals(EnvironmentRepositoryFactory.class);
}).findFirst();
.filter(i -> {
ParameterizedType parameterizedType = (ParameterizedType) i.getType();
return parameterizedType.getRawType().equals(EnvironmentRepositoryFactory.class);
})
.findFirst();
ParameterizedType factoryParameterizedType = (ParameterizedType) annotatedFactoryType
.orElse(factoryClass.getAnnotatedSuperclass()).getType();
.orElse(factoryClass.getAnnotatedSuperclass())
.getType();
return factoryParameterizedType.getActualTypeArguments();
}

View File

@@ -54,11 +54,11 @@ public class OnSearchPathLocatorPresent extends SpringBootCondition {
boolean foundSearchPathLocator = repositoryTypes.stream().anyMatch(SearchPathLocator.class::isAssignableFrom);
if (required && !foundSearchPathLocator) {
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnSearchPathLocator.class)
.notAvailable(SearchPathLocator.class.getTypeName()));
.notAvailable(SearchPathLocator.class.getTypeName()));
}
if (!required && foundSearchPathLocator) {
return ConditionOutcome.noMatch(ConditionMessage.forCondition(ConditionalOnMissingSearchPathLocator.class)
.available(SearchPathLocator.class.getTypeName()));
.available(SearchPathLocator.class.getTypeName()));
}
return ConditionOutcome.match();
}

View File

@@ -203,12 +203,19 @@ public class ConfigServerProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", enabled).append("bootstrap", bootstrap)
.append("prefix", prefix).append("defaultLabel", defaultLabel).append("overrides", overrides)
.append("stripDocumentFromYaml", stripDocumentFromYaml).append("acceptEmpty", acceptEmpty)
.append("defaultApplicationName", defaultApplicationName).append("defaultProfile", defaultProfile)
.append("failOnCompositeError", failOnCompositeError).append("encrypt", encrypt)
.append("reverseLocationOrder", reverseLocationOrder).toString();
return new ToStringCreator(this).append("enabled", enabled)
.append("bootstrap", bootstrap)
.append("prefix", prefix)
.append("defaultLabel", defaultLabel)
.append("overrides", overrides)
.append("stripDocumentFromYaml", stripDocumentFromYaml)
.append("acceptEmpty", acceptEmpty)
.append("defaultApplicationName", defaultApplicationName)
.append("defaultProfile", defaultProfile)
.append("failOnCompositeError", failOnCompositeError)
.append("encrypt", encrypt)
.append("reverseLocationOrder", reverseLocationOrder)
.toString();
}
@@ -246,8 +253,9 @@ public class ConfigServerProperties {
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", enabled).append("plainTextEncrypt", plainTextEncrypt)
.toString();
return new ToStringCreator(this).append("enabled", enabled)
.append("plainTextEncrypt", plainTextEncrypt)
.toString();
}

View File

@@ -63,39 +63,45 @@ class ConfigServerRuntimeHints implements RuntimeHintsRegistrar {
classLoader)) {
return;
}
hints.reflection().registerTypes(Set.of(TypeReference.of(HostKeyAndAlgoBothExistValidator.class),
TypeReference.of(KnownHostsFileValidator.class), TypeReference.of(HostKeyAlgoSupportedValidator.class),
TypeReference.of(PrivateKeyValidator.class), TypeReference.of(SshPropertyValidator.class),
TypeReference.of(PropertyValueDescriptor.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
hints.reflection().registerTypes(
Set.of(TypeReference.of(PropertyValueDescriptor.class), TypeReference.of(Mac.class),
TypeReference.of(KeyAgreement.class), TypeReference.of(KeyPairGenerator.class),
TypeReference.of(KeyFactory.class), TypeReference.of(Signature.class),
TypeReference.of(MessageDigest.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
hints.reflection()
.registerTypes(Set.of(TypeReference.of(HostKeyAndAlgoBothExistValidator.class),
TypeReference.of(KnownHostsFileValidator.class),
TypeReference.of(HostKeyAlgoSupportedValidator.class), TypeReference.of(PrivateKeyValidator.class),
TypeReference.of(SshPropertyValidator.class), TypeReference.of(PropertyValueDescriptor.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
hints.reflection()
.registerTypes(
Set.of(TypeReference.of(PropertyValueDescriptor.class), TypeReference.of(Mac.class),
TypeReference.of(KeyAgreement.class), TypeReference.of(KeyPairGenerator.class),
TypeReference.of(KeyFactory.class), TypeReference.of(Signature.class),
TypeReference.of(MessageDigest.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
// TODO: move over to GraalVM reachability metadata
if (ClassUtils.isPresent("org.apache.sshd.common.SshConstants", classLoader)) {
hints.reflection().registerTypes(Set.of(TypeReference.of(BouncyCastleSecurityProviderRegistrar.class),
TypeReference.of(EdDSASecurityProviderRegistrar.class), TypeReference.of(Nio2ServiceFactory.class),
TypeReference.of(Nio2ServiceFactoryFactory.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
hints.reflection().registerTypes(Set.of(TypeReference.of(PortForwardingEventListener.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS));
hints.proxies().registerJdkProxy(TypeReference.of(ChannelListener.class),
TypeReference.of(PortForwardingEventListener.class), TypeReference.of(SessionListener.class));
hints.reflection()
.registerTypes(Set.of(TypeReference.of(BouncyCastleSecurityProviderRegistrar.class),
TypeReference.of(EdDSASecurityProviderRegistrar.class),
TypeReference.of(Nio2ServiceFactory.class), TypeReference.of(Nio2ServiceFactoryFactory.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
hints.reflection()
.registerTypes(Set.of(TypeReference.of(PortForwardingEventListener.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS));
hints.proxies()
.registerJdkProxy(TypeReference.of(ChannelListener.class),
TypeReference.of(PortForwardingEventListener.class), TypeReference.of(SessionListener.class));
}
// TODO: move over to GraalVM reachability metadata
if (ClassUtils.isPresent("org.eclipse.jgit.api.Git", classLoader)) {
hints.reflection()
.registerTypes(Set.of(TypeReference.of(MergeCommand.FastForwardMode.Merge.class),
TypeReference.of(MergeCommand.ConflictStyle.class),
TypeReference.of(MergeCommand.FastForwardMode.class), TypeReference.of(FetchCommand.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
hints.reflection().registerTypes(Set.of(TypeReference.of(SshdText.class)), hint -> hint
.registerTypes(Set.of(TypeReference.of(MergeCommand.FastForwardMode.Merge.class),
TypeReference.of(MergeCommand.ConflictStyle.class),
TypeReference.of(MergeCommand.FastForwardMode.class), TypeReference.of(FetchCommand.class)),
hint -> hint.withMembers(MemberCategory.INVOKE_DECLARED_METHODS));
hints.reflection()
.registerTypes(Set.of(TypeReference.of(SshdText.class)), hint -> hint
.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.DECLARED_FIELDS));
}
}

View File

@@ -75,8 +75,8 @@ abstract class AbstractCipherResourceEncryptor implements ResourceEncryptor {
protected String decryptValue(String value, String name, String[] profiles) {
return encryptor
.locate(this.helper.getEncryptorKeys(name, StringUtils.arrayToCommaDelimitedString(profiles), value))
.decrypt(this.helper.stripPrefix(value));
.locate(this.helper.getEncryptorKeys(name, StringUtils.arrayToCommaDelimitedString(profiles), value))
.decrypt(this.helper.stripPrefix(value));
}
}

View File

@@ -69,9 +69,9 @@ public class CipherEnvironmentEncryptor implements EnvironmentEncryptor {
try {
value = value.substring("{cipher}".length());
value = encryptor
.locate(this.helper.getEncryptorKeys(name,
StringUtils.arrayToCommaDelimitedString(environment.getProfiles()), value))
.decrypt(this.helper.stripPrefix(value));
.locate(this.helper.getEncryptorKeys(name,
StringUtils.arrayToCommaDelimitedString(environment.getProfiles()), value))
.decrypt(this.helper.stripPrefix(value));
}
catch (Exception e) {
value = "<n/a>";

View File

@@ -93,8 +93,10 @@ public class AwsParameterStoreEnvironmentRepository implements EnvironmentReposi
List<String> reversedProfiles = new ArrayList<>(Arrays.asList(profiles));
Collections.reverse(reversedProfiles);
List<String> orderedProfiles = Stream.concat(reversedProfiles.stream().filter(p -> !p.equals(defaultProfile)),
Arrays.stream(new String[] { defaultProfile })).collect(Collectors.toList());
List<String> orderedProfiles = Stream
.concat(reversedProfiles.stream().filter(p -> !p.equals(defaultProfile)),
Arrays.stream(new String[] { defaultProfile }))
.collect(Collectors.toList());
if (application.equals(defaultApplication)) {
for (String profile : orderedProfiles) {
@@ -143,9 +145,12 @@ public class AwsParameterStoreEnvironmentRepository implements EnvironmentReposi
private Map<String, String> getPropertiesByParameterPath(String path) {
Map<String, String> result = new HashMap<>();
GetParametersByPathRequest request = GetParametersByPathRequest.builder().path(path)
.recursive(environmentProperties.isRecursive()).withDecryption(environmentProperties.isDecryptValues())
.maxResults(environmentProperties.getMaxResults()).build();
GetParametersByPathRequest request = GetParametersByPathRequest.builder()
.path(path)
.recursive(environmentProperties.isRecursive())
.withDecryption(environmentProperties.isDecryptValues())
.maxResults(environmentProperties.getMaxResults())
.build();
GetParametersByPathResponse response = awsSsmClient.getParametersByPath(request);
@@ -154,7 +159,7 @@ public class AwsParameterStoreEnvironmentRepository implements EnvironmentReposi
while (StringUtils.hasLength(response.nextToken())) {
response = awsSsmClient
.getParametersByPath(request.toBuilder().nextToken(response.nextToken()).build());
.getParametersByPath(request.toBuilder().nextToken(response.nextToken()).build());
addParametersToProperties(path, response.parameters(), result);
}

View File

@@ -54,8 +54,8 @@ public class CompositeEnvironmentRepository implements EnvironmentRepository {
Collections.sort(environmentRepositories, OrderComparator.INSTANCE);
this.environmentRepositories = observationRegistry.isNoop() ? environmentRepositories
: environmentRepositories.stream()
.map(e -> ObservationEnvironmentRepositoryWrapper.wrap(observationRegistry, e))
.collect(Collectors.toList());
.map(e -> ObservationEnvironmentRepositoryWrapper.wrap(observationRegistry, e))
.collect(Collectors.toList());
this.failOnError = failOnError;
}
@@ -79,8 +79,8 @@ public class CompositeEnvironmentRepository implements EnvironmentRepository {
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);
Environment envRepo = this.environmentRepositories.get(0)
.findOne(application, profile, label, includeOrigin);
env.addAll(envRepo.getPropertySources());
env.setVersion(envRepo.getVersion());
env.setState(envRepo.getState());

View File

@@ -94,12 +94,15 @@ public class CredhubEnvironmentRepository implements EnvironmentRepository, Orde
private Map<Object, Object> findProperties(String application, String profile, String label) {
String path = "/" + application + "/" + profile + "/" + label;
return this.credHubOperations.credentials().findByPath(path).stream()
.map(credentialSummary -> credentialSummary.getName().getName())
.map(name -> this.credHubOperations.credentials().getByName(new SimpleCredentialName(name),
JsonCredential.class))
.map(CredentialDetails::getValue).flatMap(jsonCredential -> jsonCredential.entrySet().stream())
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
return this.credHubOperations.credentials()
.findByPath(path)
.stream()
.map(credentialSummary -> credentialSummary.getName().getName())
.map(name -> this.credHubOperations.credentials()
.getByName(new SimpleCredentialName(name), JsonCredential.class))
.map(CredentialDetails::getValue)
.flatMap(jsonCredential -> jsonCredential.entrySet().stream())
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> b));
}
@Override

View File

@@ -307,8 +307,8 @@ public class EnvironmentController {
}
else {
String prefixKey = entry.getKey().substring(0, entry.getKey().indexOf("["));
currentArrayMap.computeIfAbsent(prefixKey, k -> new LinkedHashMap<>()).put(entry.getKey(),
entry.getValue());
currentArrayMap.computeIfAbsent(prefixKey, k -> new LinkedHashMap<>())
.put(entry.getKey(), entry.getValue());
}
}
// Override array properties by prefix key

View File

@@ -51,7 +51,7 @@ public class EnvironmentRepositoryPropertySourceLocator implements PropertySourc
public org.springframework.core.env.PropertySource<?> locate(Environment environment) {
CompositePropertySource composite = new CompositePropertySource("configService");
for (PropertySource source : this.repository.findOne(this.name, this.profiles, this.label, false)
.getPropertySources()) {
.getPropertySources()) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) source.getSource();
composite.addPropertySource(new MapPropertySource(source.getName(), map));

View File

@@ -74,7 +74,7 @@ public class GoogleSecretManagerEnvironmentRepository implements EnvironmentRepo
profile = "default," + profile;
}
String[] profiles = org.springframework.util.StringUtils
.trimArrayElements(org.springframework.util.StringUtils.commaDelimitedListToStringArray(profile));
.trimArrayElements(org.springframework.util.StringUtils.commaDelimitedListToStringArray(profile));
Environment result = new Environment(application, profile, label, null, null);
if (tokenMandatory) {
if (accessStrategy.checkRemotePermissions()) {

View File

@@ -117,8 +117,10 @@ public class HttpClientConfigurableHttpConnectionFactory implements Configurable
* which have no placeholders. That is the one we want to use in the case
* there are multiple matches.
*/
List<String> keys = builderMap.keySet().stream().filter(key -> !PLACEHOLDER_PATTERN.matcher(key).find())
.collect(Collectors.toList());
List<String> keys = builderMap.keySet()
.stream()
.filter(key -> !PLACEHOLDER_PATTERN.matcher(key).find())
.collect(Collectors.toList());
if (keys.size() == 1) {
return builderMap.get(keys.get(0));

View File

@@ -446,10 +446,10 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
private List<String> deleteBranches(Git git, Collection<String> branchesToDelete) throws GitAPIException {
DeleteBranchCommand deleteBranchCommand = git.branchDelete()
.setBranchNames(branchesToDelete.toArray(new String[0]))
// local branch can contain data which is not merged to HEAD - force
// delete it anyway, since local copy should be R/O
.setForce(true);
.setBranchNames(branchesToDelete.toArray(new String[0]))
// local branch can contain data which is not merged to HEAD - force
// delete it anyway, since local copy should be R/O
.setForce(true);
List<String> resultList = deleteBranchCommand.call();
this.logger.info(format("Deleted %s branches from %s branches to delete.", resultList, branchesToDelete));
return resultList;
@@ -651,8 +651,9 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
}
private Git cloneToBasedir() throws GitAPIException {
CloneCommand clone = this.gitFactory.getCloneCommandByCloneRepository().setURI(getUri())
.setDirectory(getBasedir());
CloneCommand clone = this.gitFactory.getCloneCommandByCloneRepository()
.setURI(getUri())
.setDirectory(getBasedir());
configureCommand(clone);
try {
return clone.call();
@@ -709,8 +710,10 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository
}
private void trackBranch(Git git, CheckoutCommand checkout, String label) {
checkout.setCreateBranch(true).setName(label).setUpstreamMode(SetupUpstreamMode.TRACK)
.setStartPoint("origin/" + label);
checkout.setCreateBranch(true)
.setName(label)
.setUpstreamMode(SetupUpstreamMode.TRACK)
.setStartPoint("origin/" + label);
}
private boolean isBranch(Git git, String label) throws GitAPIException {

View File

@@ -62,8 +62,9 @@ public class MultipleJGitEnvironmentRepository extends JGitEnvironmentRepository
MultipleJGitEnvironmentProperties properties, ObservationRegistry observationRegistry) {
super(environment, properties, observationRegistry);
this.observationRegistry = observationRegistry;
properties.getRepos().forEach((name, props) -> this.repos.put(name,
new PatternMatchingJGitEnvironmentRepository(environment, props, this.observationRegistry)));
properties.getRepos()
.forEach((name, props) -> this.repos.put(name,
new PatternMatchingJGitEnvironmentRepository(environment, props, this.observationRegistry)));
}
@Override

View File

@@ -98,7 +98,7 @@ public class MultipleJGitEnvironmentRepositoryFactory
}
repository.setGitCredentialsProviderFactory(gitCredentialsProviderFactory);
repository.getRepos()
.forEach((name, repo) -> repo.setGitCredentialsProviderFactory(gitCredentialsProviderFactory));
.forEach((name, repo) -> repo.setGitCredentialsProviderFactory(gitCredentialsProviderFactory));
return repository;
}

View File

@@ -154,8 +154,8 @@ public class NativeEnvironmentRepository implements EnvironmentRepository, Searc
environment.getPropertySources().remove("config-data-setup");
return clean(ObservationEnvironmentRepositoryWrapper
.wrap(this.observationRegistry, new PassthruEnvironmentRepository(environment))
.findOne(config, profile, label, includeOrigin), propertySourceToConfigData);
.wrap(this.observationRegistry, new PassthruEnvironmentRepository(environment))
.findOne(config, profile, label, includeOrigin), propertySourceToConfigData);
}
catch (Exception e) {
String msg = String.format("Could not construct context for config=%s profile=%s label=%s includeOrigin=%b",
@@ -338,8 +338,9 @@ public class NativeEnvironmentRepository implements EnvironmentRepository, Searc
break;
}
if (locations != null) {
matches = Arrays.stream(locations).map(this::cleanFileLocation)
.anyMatch(location -> location.startsWith(finalPattern));
matches = Arrays.stream(locations)
.map(this::cleanFileLocation)
.anyMatch(location -> location.startsWith(finalPattern));
if (matches) {
break;
}

View File

@@ -62,8 +62,8 @@ public final class ObservationEnvironmentRepositoryWrapper implements Environmen
ObservationEnvironmentRepositoryContext context = new ObservationEnvironmentRepositoryContext(
this.delegate.getClass(), application, profile, label);
return DocumentedConfigObservation.ENVIRONMENT_REPOSITORY
.observation(null, CONVENTION, () -> context, this.registry)
.observe(() -> this.delegate.findOne(application, profile, label));
.observation(null, CONVENTION, () -> context, this.registry)
.observe(() -> this.delegate.findOne(application, profile, label));
}
@Override
@@ -71,8 +71,8 @@ public final class ObservationEnvironmentRepositoryWrapper implements Environmen
ObservationEnvironmentRepositoryContext context = new ObservationEnvironmentRepositoryContext(
this.delegate.getClass(), application, profile, label);
return DocumentedConfigObservation.ENVIRONMENT_REPOSITORY
.observation(null, CONVENTION, () -> context, this.registry)
.observe(() -> this.delegate.findOne(application, profile, label, includeOrigin));
.observation(null, CONVENTION, () -> context, this.registry)
.observe(() -> this.delegate.findOne(application, profile, label, includeOrigin));
}
/**

View File

@@ -153,8 +153,9 @@ public class SvnKitEnvironmentRepository extends AbstractScmEnvironmentRepositor
}
}
final SVNStatus status = SVNClientManager.newInstance().getStatusClient().doStatus(getWorkingDirectory(),
false);
final SVNStatus status = SVNClientManager.newInstance()
.getStatusClient()
.doStatus(getWorkingDirectory(), false);
return status != null ? status.getRevision().toString() : null;
}

View File

@@ -74,7 +74,8 @@ public class GoogleSecretManagerV1AccessStrategy implements GoogleSecretManagerA
if (StringUtils.isNotEmpty(serviceAccountFile)) {
GoogleCredentials creds = GoogleCredentials.fromStream(new FileInputStream(new File(serviceAccountFile)));
this.client = SecretManagerServiceClient.create(SecretManagerServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(creds)).build());
.setCredentialsProvider(FixedCredentialsProvider.create(creds))
.build());
}
else {
this.client = SecretManagerServiceClient.create();
@@ -100,7 +101,7 @@ public class GoogleSecretManagerV1AccessStrategy implements GoogleSecretManagerA
// Get all secrets.
SecretManagerServiceClient.ListSecretsPagedResponse pagedListSecretResponse = client
.listSecrets(listSecretRequest);
.listSecrets(listSecretRequest);
List<Secret> result = new ArrayList<Secret>();
pagedListSecretResponse.iterateAll().forEach(result::add);
@@ -114,11 +115,12 @@ public class GoogleSecretManagerV1AccessStrategy implements GoogleSecretManagerA
// Create the request.
ListSecretVersionsRequest listVersionRequest = ListSecretVersionsRequest.newBuilder()
.setParent(parent.toString()).build();
.setParent(parent.toString())
.build();
// Get all versions.
SecretManagerServiceClient.ListSecretVersionsPagedResponse pagedListVersionResponse = client
.listSecretVersions(listVersionRequest);
.listSecretVersions(listVersionRequest);
List<SecretVersion> result = new ArrayList<SecretVersion>();
pagedListVersionResponse.iterateAll().forEach(result::add);
return result;
@@ -138,8 +140,9 @@ public class GoogleSecretManagerV1AccessStrategy implements GoogleSecretManagerA
if (winner != null) {
SecretVersionName name = SecretVersionName.parse(winner.getName());
// Access the secret version.
AccessSecretVersionRequest request = AccessSecretVersionRequest.newBuilder().setName(name.toString())
.build();
AccessSecretVersionRequest request = AccessSecretVersionRequest.newBuilder()
.setName(name.toString())
.build();
AccessSecretVersionResponse response = client.accessSecretVersion(request);
result = response.getPayload().getData().toStringUtf8();
}
@@ -160,14 +163,16 @@ public class GoogleSecretManagerV1AccessStrategy implements GoogleSecretManagerA
GoogleCredentials credential = new GoogleCredentials(accessToken);
HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential);
service = new CloudResourceManager.Builder(GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(), requestInitializer).setApplicationName(APPLICATION_NAME)
.build();
JacksonFactory.getDefaultInstance(), requestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
List<String> permissionsList = Arrays.asList(ACCESS_SECRET_PERMISSION);
TestIamPermissionsRequest requestBody = new TestIamPermissionsRequest().setPermissions(permissionsList);
TestIamPermissionsResponse testIamPermissionsResponse = service.projects()
.testIamPermissions(getProjectId(), requestBody).execute();
.testIamPermissions(getProjectId(), requestBody)
.execute();
if (testIamPermissionsResponse.getPermissions() != null && testIamPermissionsResponse.size() >= 1) {
return Boolean.TRUE;
@@ -198,8 +203,10 @@ public class GoogleSecretManagerV1AccessStrategy implements GoogleSecretManagerA
catch (Exception e) {
// not in GCP
HttpEntity<String> entity = new HttpEntity<String>("parameters", getMetadataHttpHeaders());
result = rest.exchange(GoogleSecretManagerEnvironmentProperties.GOOGLE_METADATA_PROJECT_URL, HttpMethod.GET,
entity, String.class).getBody();
result = rest
.exchange(GoogleSecretManagerEnvironmentProperties.GOOGLE_METADATA_PROJECT_URL, HttpMethod.GET, entity,
String.class)
.getBody();
}
return result;
}

View File

@@ -76,8 +76,12 @@ public class SpringVaultClientConfiguration extends AbstractVaultConfiguration {
@Override
public VaultEndpoint vaultEndpoint() {
URI baseUrl = UriComponentsBuilder.newInstance().scheme(vaultProperties.getScheme())
.host(vaultProperties.getHost()).port(vaultProperties.getPort()).build().toUri();
URI baseUrl = UriComponentsBuilder.newInstance()
.scheme(vaultProperties.getScheme())
.host(vaultProperties.getHost())
.port(vaultProperties.getPort())
.build()
.toUri();
return VaultEndpoint.from(baseUrl);
}
@@ -125,7 +129,8 @@ public class SpringVaultClientConfiguration extends AbstractVaultConfiguration {
@Override
public RestOperations restOperations() {
return restTemplateBuilder(vaultEndpointProvider(),
clientHttpRequestFactoryWrapper().getClientHttpRequestFactory()).build();
clientHttpRequestFactoryWrapper().getClientHttpRequestFactory())
.build();
}
private SslConfiguration.KeyStoreConfiguration getKeyStoreConfiguration(Resource resourceProperty,

View File

@@ -46,7 +46,8 @@ public class AppRoleClientAuthenticationProvider extends SpringVaultClientAuthen
VaultEnvironmentProperties.AppRoleProperties appRole = vaultProperties.getAppRole();
AppRoleAuthenticationOptions.AppRoleAuthenticationOptionsBuilder builder = AppRoleAuthenticationOptions
.builder().path(appRole.getAppRolePath());
.builder()
.path(appRole.getAppRolePath());
if (StringUtils.hasText(appRole.getRole())) {
builder.appRole(appRole.getRole());

View File

@@ -43,11 +43,12 @@ public class AwsEc2ClientAuthenticationProvider extends SpringVaultClientAuthent
? AwsEc2AuthenticationOptions.Nonce.provided(awsEc2.getNonce().toCharArray())
: AwsEc2AuthenticationOptions.Nonce.generated();
AwsEc2AuthenticationOptions authenticationOptions = AwsEc2AuthenticationOptions.builder().role(awsEc2.getRole()) //
.path(awsEc2.getAwsEc2Path()) //
.nonce(nonce) //
.identityDocumentUri(URI.create(awsEc2.getIdentityDocument())) //
.build();
AwsEc2AuthenticationOptions authenticationOptions = AwsEc2AuthenticationOptions.builder()
.role(awsEc2.getRole()) //
.path(awsEc2.getAwsEc2Path()) //
.nonce(nonce) //
.identityDocumentUri(URI.create(awsEc2.getIdentityDocument())) //
.build();
return new AwsEc2Authentication(authenticationOptions, vaultRestOperations, externalRestOperations);
}

View File

@@ -63,7 +63,7 @@ public class AwsIamClientAuthenticationProvider extends SpringVaultClientAuthent
}
builder.path(awsIam.getAwsPath()) //
.credentialsProvider(credentialsProvider);
.credentialsProvider(credentialsProvider);
AwsIamAuthenticationOptions options = builder.credentialsProvider(credentialsProvider).build();

View File

@@ -42,13 +42,14 @@ public class AzureMsiClientAuthenticationProvider extends SpringVaultClientAuthe
Assert.hasText(azureMsi.getRole(),
missingPropertyForAuthMethod("azure-msi.role", AuthenticationMethod.AZURE_MSI));
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder().role(azureMsi.getRole())
.path(azureMsi.getAzurePath())
.instanceMetadataUri(getUri(azureMsi.getMetadataService(),
AzureMsiAuthenticationOptions.DEFAULT_INSTANCE_METADATA_SERVICE_URI))
.identityTokenServiceUri(getUri(azureMsi.getIdentityTokenService(),
AzureMsiAuthenticationOptions.DEFAULT_IDENTITY_TOKEN_SERVICE_URI))
.build();
AzureMsiAuthenticationOptions options = AzureMsiAuthenticationOptions.builder()
.role(azureMsi.getRole())
.path(azureMsi.getAzurePath())
.instanceMetadataUri(getUri(azureMsi.getMetadataService(),
AzureMsiAuthenticationOptions.DEFAULT_INSTANCE_METADATA_SERVICE_URI))
.identityTokenServiceUri(getUri(azureMsi.getIdentityTokenService(),
AzureMsiAuthenticationOptions.DEFAULT_IDENTITY_TOKEN_SERVICE_URI))
.build();
return new AzureMsiAuthentication(options, vaultRestOperations, externalRestOperations);
}

View File

@@ -41,9 +41,9 @@ public class CubbyholeClientAuthenticationProvider extends SpringVaultClientAuth
Assert.hasText(token, missingPropertyForAuthMethod("token", AuthenticationMethod.CUBBYHOLE));
CubbyholeAuthenticationOptions options = CubbyholeAuthenticationOptions.builder() //
.wrapped() //
.initialToken(VaultToken.of(token)) //
.build();
.wrapped() //
.initialToken(VaultToken.of(token)) //
.build();
return new CubbyholeAuthentication(options, vaultRestOperations);
}

View File

@@ -41,7 +41,9 @@ public class GcpGceClientAuthenticationProvider extends SpringVaultClientAuthent
Assert.hasText(gcp.getRole(), missingPropertyForAuthMethod("gcp-iam.role", AuthenticationMethod.GCP_GCE));
GcpComputeAuthenticationOptions.GcpComputeAuthenticationOptionsBuilder builder = GcpComputeAuthenticationOptions
.builder().path(gcp.getGcpPath()).role(gcp.getRole());
.builder()
.path(gcp.getGcpPath())
.role(gcp.getRole());
if (StringUtils.hasText(gcp.getServiceAccount())) {
builder.serviceAccount(gcp.getServiceAccount());

View File

@@ -50,7 +50,9 @@ public class GcpIamClientAuthenticationProvider extends SpringVaultClientAuthent
Assert.hasText(gcp.getRole(), missingPropertyForAuthMethod("gcp-iam.role", AuthenticationMethod.GCP_IAM));
GcpIamAuthenticationOptions.GcpIamAuthenticationOptionsBuilder builder = GcpIamAuthenticationOptions.builder()
.path(gcp.getGcpPath()).role(gcp.getRole()).jwtValidity(gcp.getJwtValidity());
.path(gcp.getGcpPath())
.role(gcp.getRole())
.jwtValidity(gcp.getJwtValidity());
if (StringUtils.hasText(gcp.getProjectId())) {
builder.projectId(gcp.getProjectId());

View File

@@ -44,8 +44,10 @@ public class KubernetesClientAuthenticationProvider extends SpringVaultClientAut
missingPropertyForAuthMethod("kubernetes.service-account-token-file", AuthenticationMethod.KUBERNETES));
KubernetesAuthenticationOptions options = KubernetesAuthenticationOptions.builder()
.path(kubernetes.getKubernetesPath()).role(kubernetes.getRole())
.jwtSupplier(new KubernetesServiceAccountTokenFile(kubernetes.getServiceAccountTokenFile())).build();
.path(kubernetes.getKubernetesPath())
.role(kubernetes.getRole())
.jwtSupplier(new KubernetesServiceAccountTokenFile(kubernetes.getServiceAccountTokenFile()))
.build();
return new KubernetesAuthentication(options, vaultRestOperations);
}

View File

@@ -44,7 +44,8 @@ public class PcfClientAuthenticationProvider extends SpringVaultClientAuthentica
Assert.hasText(pcfProperties.getRole(), missingPropertyForAuthMethod("pcf.role", AuthenticationMethod.PCF));
PcfAuthenticationOptions.PcfAuthenticationOptionsBuilder builder = PcfAuthenticationOptions.builder()
.role(pcfProperties.getRole()).path(pcfProperties.getPcfPath());
.role(pcfProperties.getRole())
.path(pcfProperties.getPcfPath());
if (pcfProperties.getInstanceCertificate() != null) {
builder.instanceCertificate(new ResourceCredentialSupplier(pcfProperties.getInstanceCertificate()));

View File

@@ -40,7 +40,7 @@ public class FileBasedSshTransportConfigCallback implements TransportConfigCallb
public FileBasedSshTransportConfigCallback(MultipleJGitEnvironmentProperties sshUriProperties) {
this.sshUriProperties = sshUriProperties;
Map<String, JGitEnvironmentProperties> sshKeysByHostname = new SshUriPropertyProcessor(this.sshUriProperties)
.getSshKeysByHostname();
.getSshKeysByHostname();
if (sshKeysByHostname.isEmpty()) {
this.sshdSessionFactory = null;
}

View File

@@ -63,7 +63,7 @@ public class HostKeyAlgoSupportedValidator
context.disableDefaultConstraintViolation();
Set<Boolean> validationResults = new HashSet<>();
List<JGitEnvironmentProperties> extractedProperties = this.sshPropertyValidator
.extractRepoProperties(sshUriProperties);
.extractRepoProperties(sshUriProperties);
for (JGitEnvironmentProperties extractedProperty : extractedProperties) {
if (sshUriProperties.isIgnoreLocalSshSettings() && isSshUri(extractedProperty.getUri())) {
@@ -78,8 +78,10 @@ public class HostKeyAlgoSupportedValidator
if (hasText(sshUriProperties.getHostKeyAlgorithm())
&& !VALID_HOST_KEY_ALGORITHMS.contains(sshUriProperties.getHostKeyAlgorithm())) {
context.buildConstraintViolationWithTemplate(format("Property '%shostKeyAlgorithm' must be one of %s",
GIT_PROPERTY_PREFIX, VALID_HOST_KEY_ALGORITHMS)).addConstraintViolation();
context
.buildConstraintViolationWithTemplate(format("Property '%shostKeyAlgorithm' must be one of %s",
GIT_PROPERTY_PREFIX, VALID_HOST_KEY_ALGORITHMS))
.addConstraintViolation();
return false;
}
return true;

View File

@@ -29,6 +29,7 @@ import org.springframework.validation.annotation.Validated;
/**
* Beans annotated with {@link HostKeyAndAlgoBothExist} and {@link Validated} will have
* the constraints applied.
*
* @author Ollie Hughes
*/
@Constraint(validatedBy = HostKeyAndAlgoBothExistValidator.class)

View File

@@ -58,7 +58,7 @@ public class HostKeyAndAlgoBothExistValidator
public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, ConstraintValidatorContext context) {
Set<Boolean> validationResults = new HashSet<>();
List<JGitEnvironmentProperties> extractedProperties = this.sshPropertyValidator
.extractRepoProperties(sshUriProperties);
.extractRepoProperties(sshUriProperties);
for (JGitEnvironmentProperties extractedProperty : extractedProperties) {
if (sshUriProperties.isIgnoreLocalSshSettings() && isSshUri(extractedProperty.getUri())) {
@@ -73,10 +73,11 @@ public class HostKeyAndAlgoBothExistValidator
ConstraintValidatorContext context) {
if (hasText(sshUriProperties.getHostKeyAlgorithm()) && !hasText(sshUriProperties.getHostKey())) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
format("Property '%shostKey' must be set when '%shostKeyAlgorithm' is specified",
GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX))
.addConstraintViolation();
context
.buildConstraintViolationWithTemplate(
format("Property '%shostKey' must be set when '%shostKeyAlgorithm' is specified",
GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX))
.addConstraintViolation();
return false;
}
return true;
@@ -86,10 +87,11 @@ public class HostKeyAndAlgoBothExistValidator
ConstraintValidatorContext context) {
if (hasText(sshUriProperties.getHostKey()) && !hasText(sshUriProperties.getHostKeyAlgorithm())) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
format("Property '%shostKeyAlgorithm' must be set when '%shostKey' is specified",
GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX))
.addConstraintViolation();
context
.buildConstraintViolationWithTemplate(
format("Property '%shostKeyAlgorithm' must be set when '%shostKey' is specified",
GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX))
.addConstraintViolation();
return false;
}
return true;

View File

@@ -51,7 +51,8 @@ public class KnownHostsFileValidator
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(format(
"File '%s' specified in property 'spring.cloud.config.server.git.knownHostsFile' could not be located",
knownHostsFile)).addConstraintViolation();
knownHostsFile))
.addConstraintViolation();
return false;
}
return true;

View File

@@ -57,7 +57,7 @@ public class PrivateKeyValidator implements ConstraintValidator<PrivateKeyIsVali
context.disableDefaultConstraintViolation();
Set<Boolean> validationResults = new HashSet<>();
List<JGitEnvironmentProperties> extractedProperties = this.sshPropertyValidator
.extractRepoProperties(sshUriProperties);
.extractRepoProperties(sshUriProperties);
for (JGitEnvironmentProperties extractedProperty : extractedProperties) {
if (extractedProperty.isIgnoreLocalSshSettings() && isSshUri(extractedProperty.getUri())) {
@@ -72,10 +72,11 @@ public class PrivateKeyValidator implements ConstraintValidator<PrivateKeyIsVali
private boolean isPrivateKeyPresent(JGitEnvironmentProperties sshUriProperties,
ConstraintValidatorContext context) {
if (!hasText(sshUriProperties.getPrivateKey())) {
context.buildConstraintViolationWithTemplate(
format("Property '%sprivateKey' must be set when '%signoreLocalSshSettings' is specified",
GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX))
.addConstraintViolation();
context
.buildConstraintViolationWithTemplate(
format("Property '%sprivateKey' must be set when '%signoreLocalSshSettings' is specified",
GIT_PROPERTY_PREFIX, GIT_PROPERTY_PREFIX))
.addConstraintViolation();
return false;
}
return true;
@@ -87,9 +88,10 @@ public class PrivateKeyValidator implements ConstraintValidator<PrivateKeyIsVali
return true;
}
context.buildConstraintViolationWithTemplate(
format("Property '%sprivateKey' is not a valid private key", GIT_PROPERTY_PREFIX))
.addConstraintViolation();
context
.buildConstraintViolationWithTemplate(
format("Property '%sprivateKey' is not a valid private key", GIT_PROPERTY_PREFIX))
.addConstraintViolation();
return false;
}

View File

@@ -40,7 +40,7 @@ public class PropertiesBasedSshTransportConfigCallback implements TransportConfi
public PropertiesBasedSshTransportConfigCallback(MultipleJGitEnvironmentProperties sshUriProperties) {
this.sshUriProperties = sshUriProperties;
Map<String, JGitEnvironmentProperties> sshKeysByHostname = new SshUriPropertyProcessor(this.sshUriProperties)
.getSshKeysByHostname();
.getSshKeysByHostname();
if (sshKeysByHostname.isEmpty()) {
this.sshdSessionFactory = null;
}

View File

@@ -164,7 +164,7 @@ public class PropertyBasedSshSessionFactory extends SshdSessionFactory {
try {
return AuthorizedKeyEntry.parseAuthorizedKeyEntry(hostKeyAlgorithm + " " + hostKey)
.resolvePublicKey(null, null);
.resolvePublicKey(null, null);
}
catch (IOException | GeneralSecurityException e) {
throw new RuntimeException(e);
@@ -236,7 +236,7 @@ public class PropertyBasedSshSessionFactory extends SshdSessionFactory {
JGitEnvironmentProperties sshProperties = findEnvironmentProperties(sshKeysByHostname, remoteAddress);
ProxyHostProperties proxyHostProperties = sshProperties.getProxy()
.get(ProxyHostProperties.ProxyForScheme.HTTP);
.get(ProxyHostProperties.ProxyForScheme.HTTP);
if (proxyHostProperties == null || !proxyHostProperties.connectionInformationProvided()) {
return null;

View File

@@ -64,7 +64,7 @@ public class SshPropertyValidator {
List<JGitEnvironmentProperties> allRepoProperties = new ArrayList<>();
allRepoProperties.add(sshUriProperties);
Map<String, MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties> repos = sshUriProperties
.getRepos();
.getRepos();
if (repos != null) {
allRepoProperties.addAll(repos.values());
}

View File

@@ -64,10 +64,10 @@ public class SshUriPropertyProcessor {
sshUriPropertyMap.put(getHostname(parentUri), uriProperties);
}
Map<String, MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties> repos = uriProperties
.getRepos();
.getRepos();
if (repos != null) {
for (MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties repoProperties : repos
.values()) {
.values()) {
String repoUri = repoProperties.getUri();
if (isSshUri(repoUri) && getHostname(repoUri) != null) {
sshUriPropertyMap.put(getHostname(repoUri), repoProperties);

View File

@@ -119,9 +119,14 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider {
String codeCommitPassword;
try {
StringBuilder stringToSign = new StringBuilder();
stringToSign.append("AWS4-HMAC-SHA256\n").append(dateStamp).append("\n").append(shortDateStamp).append("/")
.append(region).append("/codecommit/aws4_request\n")
.append(bytesToHexString(canonicalRequestDigest(uri)));
stringToSign.append("AWS4-HMAC-SHA256\n")
.append(dateStamp)
.append("\n")
.append(shortDateStamp)
.append("/")
.append(region)
.append("/codecommit/aws4_request\n")
.append(bytesToHexString(canonicalRequestDigest(uri)));
byte[] signedRequest = sign(awsSecretKey, shortDateStamp, region, stringToSign.toString());
codeCommitPassword = dateStamp + "Z" + bytesToHexString(signedRequest);
@@ -158,18 +163,22 @@ public class AwsCodeCommitCredentialProvider extends CredentialsProvider {
private static byte[] canonicalRequestDigest(URIish uri) throws NoSuchAlgorithmException {
StringBuilder canonicalRequest = new StringBuilder();
canonicalRequest.append("GIT\n") // codecommit uses GIT as the request method
.append(uri.getPath()).append("\n") // URI request path
.append("\n") // Query string, always empty for codecommit
// Next is canonical headers, codecommit only requires the host header
.append("host:").append(uri.getHost()).append("\n").append("\n") // canonical
// headers
// are
// always
// terminated
// by
// newline
.append("host\n"); // The list of canonical headers, only one for
// codecommit
.append(uri.getPath())
.append("\n") // URI request path
.append("\n") // Query string, always empty for codecommit
// Next is canonical headers, codecommit only requires the host header
.append("host:")
.append(uri.getHost())
.append("\n")
.append("\n") // canonical
// headers
// are
// always
// terminated
// by
// newline
.append("host\n"); // The list of canonical headers, only one for
// codecommit
MessageDigest digest = MessageDigest.getInstance(SHA_256);

View File

@@ -78,7 +78,7 @@ public class GitSkipSslValidationCredentialsProvider extends CredentialsProvider
if (item instanceof CredentialItem.YesNoType && item.getPromptText() != null
&& (item.getPromptText().equals(JGitText.get().sslTrustNow)
|| item.getPromptText()
.startsWith(stripFormattingPlaceholders(JGitText.get().sslTrustForRepo))
.startsWith(stripFormattingPlaceholders(JGitText.get().sslTrustForRepo))
|| item.getPromptText().equals(JGitText.get().sslTrustAlways))) {
continue;
}

View File

@@ -119,8 +119,11 @@ public final class GoogleCloudSourceSupport {
@Override
public Map<String, String> getAuthorizationHeaders() {
try {
return GoogleCredentials.getApplicationDefault().getRequestMetadata().entrySet().stream()
.collect(toMap(Entry::getKey, this::joinValues));
return GoogleCredentials.getApplicationDefault()
.getRequestMetadata()
.entrySet()
.stream()
.collect(toMap(Entry::getKey, this::joinValues));
}
catch (IOException ex) {
throw new IllegalStateException(ex);

View File

@@ -66,9 +66,9 @@ public final class HttpClient4Support {
if (!CollectionUtils.isEmpty(environmentProperties.getProxy())) {
ProxyHostProperties httpsProxy = environmentProperties.getProxy()
.get(ProxyHostProperties.ProxyForScheme.HTTPS);
.get(ProxyHostProperties.ProxyForScheme.HTTPS);
ProxyHostProperties httpProxy = environmentProperties.getProxy()
.get(ProxyHostProperties.ProxyForScheme.HTTP);
.get(ProxyHostProperties.ProxyForScheme.HTTP);
httpClientBuilder.setRoutePlanner(new SchemeBasedRoutePlanner4(httpsProxy, httpProxy));
httpClientBuilder.setDefaultCredentialsProvider(new ProxyHostCredentialsProvider4(httpProxy, httpsProxy));
@@ -86,8 +86,9 @@ public final class HttpClient4Support {
httpClientBuilder.disableRedirectHandling();
int timeout = environmentProperties.getTimeout() * 1000;
httpClientBuilder.setSSLContext(sslContextBuilder.build()).setDefaultRequestConfig(
RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build());
httpClientBuilder.setSSLContext(sslContextBuilder.build())
.setDefaultRequestConfig(
RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build());
customizers.forEach(customizer -> customizer.customize(httpClientBuilder));
return httpClientBuilder;
}

View File

@@ -50,21 +50,23 @@ public final class HttpClientSupport {
throws GeneralSecurityException {
HttpClientBuilder httpClientBuilder = HttpClients.custom();
PoolingHttpClientConnectionManagerBuilder connectionManagerBuilder = PoolingHttpClientConnectionManagerBuilder
.create();
.create();
if (environmentProperties.isSkipSslValidation()) {
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
sslContextBuilder.loadTrustMaterial(null, (certificate, authType) -> true);
SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactoryBuilder.create()
.setSslContext(sslContextBuilder.build()).setHostnameVerifier(new NoopHostnameVerifier()).build();
.setSslContext(sslContextBuilder.build())
.setHostnameVerifier(new NoopHostnameVerifier())
.build();
connectionManagerBuilder.setSSLSocketFactory(sslConnectionSocketFactory);
}
if (!CollectionUtils.isEmpty(environmentProperties.getProxy())) {
ProxyHostProperties httpsProxy = environmentProperties.getProxy()
.get(ProxyHostProperties.ProxyForScheme.HTTPS);
.get(ProxyHostProperties.ProxyForScheme.HTTPS);
ProxyHostProperties httpProxy = environmentProperties.getProxy()
.get(ProxyHostProperties.ProxyForScheme.HTTP);
.get(ProxyHostProperties.ProxyForScheme.HTTP);
httpClientBuilder.setRoutePlanner(new SchemeBasedRoutePlanner(httpsProxy, httpProxy));
httpClientBuilder.setDefaultCredentialsProvider(new ProxyHostCredentialsProvider(httpProxy, httpsProxy));
@@ -83,9 +85,9 @@ public final class HttpClientSupport {
int timeout = environmentProperties.getTimeout() * 1000;
connectionManagerBuilder
.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout, TimeUnit.MILLISECONDS).build());
return httpClientBuilder.setConnectionManager(connectionManagerBuilder.build()).setDefaultRequestConfig(
RequestConfig.custom().setConnectTimeout(timeout, TimeUnit.MILLISECONDS).build());
.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout, TimeUnit.MILLISECONDS).build());
return httpClientBuilder.setConnectionManager(connectionManagerBuilder.build())
.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(timeout, TimeUnit.MILLISECONDS).build());
}
}

View File

@@ -64,7 +64,8 @@ public class AwsS3IntegrationTests {
@Container
static LocalStackContainer localstack = new LocalStackContainer(
DockerImageName.parse("localstack/localstack:1.3.1")).withServices(LocalStackContainer.Service.S3);
DockerImageName.parse("localstack/localstack:1.3.1"))
.withServices(LocalStackContainer.Service.S3);
private static ConfigurableApplicationContext server;
@@ -118,9 +119,9 @@ public class AwsS3IntegrationTests {
Environment env = rest.getForObject(configServerUrl + "/application/default", Environment.class);
assertThat(env.getPropertySources().get(0).getSource().get("foo")).isEqualTo("1");
assertThat(rest.getForObject(configServerUrl + "/application/default/main/data.txt", String.class))
.isEqualTo("this is a test in main");
.isEqualTo("this is a test in main");
assertThat(rest.getForObject(configServerUrl + "/application/default/data.txt?useDefaultLabel", String.class))
.isEqualTo("this is a test");
.isEqualTo("this is a test");
}
@Test
@@ -139,8 +140,10 @@ public class AwsS3IntegrationTests {
@Bean
S3Client s3Client() {
return S3Client.builder().region(Region.of(localstack.getRegion()))
.endpointOverride(localstack.getEndpointOverride(LocalStackContainer.Service.S3)).build();
return S3Client.builder()
.region(Region.of(localstack.getRegion()))
.endpointOverride(localstack.getEndpointOverride(LocalStackContainer.Service.S3))
.build();
}
@Bean

View File

@@ -33,15 +33,15 @@ public class CompositeClasspathTests {
@Test
public void contextLoads() {
new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[1].type:svn")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[1].type:svn")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
}
}
@@ -52,14 +52,14 @@ public class CompositeClasspathTests {
@Test
public void contextLoads() {
new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
assertThat(context).doesNotHaveBean("configServerHealthIndicator");
});
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
assertThat(context).doesNotHaveBean("configServerHealthIndicator");
});
}
}
@@ -70,15 +70,15 @@ public class CompositeClasspathTests {
@Test
public void contextLoads() {
new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[1].type:svn")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[1].type:svn")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
}
}
@@ -89,15 +89,15 @@ public class CompositeClasspathTests {
@Test
public void contextLoads() {
new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[1].type:native")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[1].type:native")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
}
}
@@ -108,15 +108,15 @@ public class CompositeClasspathTests {
@Test
public void contextLoads() {
new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[0].type:svn",
"spring.cloud.config.server.composite[1].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[1].type:native")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:compositeconfigserver",
"spring.cloud.config.server.composite[0].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[0].type:svn",
"spring.cloud.config.server.composite[1].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[1].type:native")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
}
}
@@ -127,13 +127,13 @@ public class CompositeClasspathTests {
@Test
public void contextLoads() {
new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:configserver",
"spring.cloud.config.server.composite[0].uri:https://source.developers.google.com",
"spring.cloud.config.server.composite[0].type:git")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
.withPropertyValues("spring.profiles.active:test,composite", "spring.jmx.enabled=false",
"spring.config.name:configserver",
"spring.cloud.config.server.composite[0].uri:https://source.developers.google.com",
"spring.cloud.config.server.composite[0].type:git")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
}
}

View File

@@ -73,7 +73,8 @@ public class CompositeIntegrationTests {
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();
&& !environment.getPropertySources().get(1).getName().contains("svn-config-repo"))
.isTrue();
assertThat(environment.getPropertySources().get(2).getName()).contains("svn-config-repo");
ConfigServerTestUtils.assertConfigEnabled(environment);
}
@@ -161,7 +162,8 @@ public class CompositeIntegrationTests {
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();
&& !environment.getPropertySources().get(1).getName().contains("svn-config-repo"))
.isTrue();
assertThat(environment.getPropertySources().get(2).getName()).contains("svn-config-repo");
ConfigServerTestUtils.assertConfigEnabled(environment);
}

View File

@@ -70,7 +70,7 @@ public class ConfigClientBackwardsCompatibilityIntegrationTests {
@Test
public void testBackwardsCompatibleFormatWithLabel() {
Map environment = new TestRestTemplate()
.getForObject("http://localhost:" + this.port + "/foo/development/master", Map.class);
.getForObject("http://localhost:" + this.port + "/foo/development/master", Map.class);
Object value = getPropertySourceValue(environment);
assertThat(value).isInstanceOf(String.class).isEqualTo("true");
}

View File

@@ -70,14 +70,15 @@ public class ConfigClientOffIntegrationTests {
@Test
public void contextLoads() {
Environment environment = new TestRestTemplate()
.getForObject("http://localhost:" + this.port + "/foo/development/", Environment.class);
.getForObject("http://localhost:" + this.port + "/foo/development/", Environment.class);
assertThat(environment.getPropertySources()).isEmpty();
}
@Test
public void configClientDisabled() throws Exception {
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.context,
ConfigServicePropertySourceLocator.class).length).isEqualTo(0);
ConfigServicePropertySourceLocator.class).length)
.isEqualTo(0);
}
@Configuration(proxyBeanMethods = false)
@@ -88,7 +89,7 @@ public class ConfigClientOffIntegrationTests {
public EnvironmentRepository environmentRepository() {
EnvironmentRepository repository = Mockito.mock(EnvironmentRepository.class);
given(repository.findOne(anyString(), anyString(), anyString(), anyBoolean()))
.willReturn(new Environment("", ""));
.willReturn(new Environment("", ""));
return repository;
}
@@ -96,7 +97,7 @@ public class ConfigClientOffIntegrationTests {
public ResourceRepository resourceRepository() {
ResourceRepository repository = Mockito.mock(ResourceRepository.class);
given(repository.findOne(anyString(), anyString(), anyString(), anyString()))
.willReturn(new ByteArrayResource("".getBytes()));
.willReturn(new ByteArrayResource("".getBytes()));
return repository;
}

View File

@@ -81,7 +81,7 @@ public class ConfigClientOnIntegrationTests {
@Test
public void contextLoads() {
Environment environment = new TestRestTemplate()
.getForObject("http://localhost:" + this.port + "/foo/development/", Environment.class);
.getForObject("http://localhost:" + this.port + "/foo/development/", Environment.class);
assertThat(environment.getPropertySources()).isEmpty();
}
@@ -90,7 +90,8 @@ public class ConfigClientOnIntegrationTests {
@Test
public void configClientEnabled() throws Exception {
assertThat(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.context,
ConfigServicePropertySourceLocator.class).length).isEqualTo(1);
ConfigServicePropertySourceLocator.class).length)
.isEqualTo(1);
}
@Configuration(proxyBeanMethods = false)
@@ -102,7 +103,7 @@ public class ConfigClientOnIntegrationTests {
public EnvironmentRepository environmentRepository() {
EnvironmentRepository repository = Mockito.mock(EnvironmentRepository.class);
given(repository.findOne(anyString(), anyString(), anyString(), anyBoolean()))
.willReturn(new Environment("", ""));
.willReturn(new Environment("", ""));
return repository;
}
@@ -110,7 +111,7 @@ public class ConfigClientOnIntegrationTests {
public ResourceRepository resourceRepository() {
ResourceRepository repository = Mockito.mock(ResourceRepository.class);
given(repository.findOne(anyString(), anyString(), anyString(), anyString()))
.willReturn(new ByteArrayResource("".getBytes()));
.willReturn(new ByteArrayResource("".getBytes()));
return repository;
}

View File

@@ -33,7 +33,8 @@ public class ConfigServerApplicationTests {
@Test
public void contextLoads() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder(ConfigServerApplication.class)
.properties("spring.config.name=configserver").run("--server.port=0")) {
.properties("spring.config.name=configserver")
.run("--server.port=0")) {
// empty
}
}

View File

@@ -42,7 +42,7 @@ public class CredhubCompositeConfigServerIntegrationTests extends CredhubIntegra
@Test
public void shouldRetrieveValuesFromCredhub() {
Environment environment = new TestRestTemplate()
.getForObject("http://localhost:" + this.port + "/myapp/master/default", Environment.class);
.getForObject("http://localhost:" + this.port + "/myapp/master/default", Environment.class);
assertThat(environment.getPropertySources()).isNotEmpty();
assertThat(environment.getPropertySources().get(0).getName()).isEqualTo("credhub-myapp-master-default");

View File

@@ -40,7 +40,7 @@ public class CredhubConfigServerIntegrationTests extends CredhubIntegrationTest
@Test
public void shouldRetrieveValuesFromCredhub() {
Environment environment = new TestRestTemplate()
.getForObject("http://localhost:" + this.port + "/myapp/master/default", Environment.class);
.getForObject("http://localhost:" + this.port + "/myapp/master/default", Environment.class);
assertThat(environment.getPropertySources()).isNotEmpty();
assertThat(environment.getPropertySources().get(0).getName()).isEqualTo("credhub-myapp-master-default");

View File

@@ -46,12 +46,12 @@ public class CredhubIntegrationTest {
String expectedPath = "/myapp/master/default";
SimpleCredentialName togglesCredentialName = new SimpleCredentialName(expectedPath + "/toggles");
when(credhubCredentialOperations.findByPath(expectedPath))
.thenReturn(singletonList(new CredentialSummary(togglesCredentialName)));
.thenReturn(singletonList(new CredentialSummary(togglesCredentialName)));
JsonCredential credentials = new JsonCredential();
credentials.put("key", "value");
when(credhubCredentialOperations.getByName(new SimpleCredentialName(expectedPath + "/toggles"),
JsonCredential.class)).thenReturn(
new CredentialDetails<>("id1", togglesCredentialName, CredentialType.JSON, credentials));
JsonCredential.class))
.thenReturn(new CredentialDetails<>("id1", togglesCredentialName, CredentialType.JSON, credentials));
when(this.credHubOperations.credentials()).thenReturn(credhubCredentialOperations);
}

View File

@@ -80,7 +80,7 @@ public class NativeConfigServerIntegrationTests {
@Test
public void badYaml() {
ResponseEntity<String> response = new TestRestTemplate()
.getForEntity("http://localhost:" + this.port + "/bad/default", String.class);
.getForEntity("http://localhost:" + this.port + "/bad/default", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}

View File

@@ -91,46 +91,48 @@ class ObservationIntegrationTests {
List<FinishedSpan> finishedSpans = finishedSpans();
SpansAssert.then(finishedSpans).hasASpanWithNameIgnoreCase("env find", spanAssert -> spanAssert
SpansAssert.then(finishedSpans)
.hasASpanWithNameIgnoreCase("env find", spanAssert -> spanAssert
.hasTag("spring.cloud.config.environment.application", "foo")
.hasTag("spring.cloud.config.environment.profile", "development")
.hasTag("spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.SearchPathCompositeEnvironmentRepository"))
.hasASpanWithNameIgnoreCase("env find", spanAssert -> spanAssert
.hasTag("spring.cloud.config.environment.application", "foo")
.hasTag("spring.cloud.config.environment.profile", "development")
.hasTag("spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository"))
.hasASpanWithNameIgnoreCase("env find", spanAssert -> spanAssert
.hasTag("spring.cloud.config.environment.application", "foo")
.hasASpanWithNameIgnoreCase("env find", spanAssert -> spanAssert
.hasTag("spring.cloud.config.environment.application", "foo")
.hasTag("spring.cloud.config.environment.profile", "development")
.hasTag("spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository"))
.hasASpanWithNameIgnoreCase("env find",
spanAssert -> spanAssert.hasTag("spring.cloud.config.environment.application", "foo")
.hasTag("spring.cloud.config.environment.profile", "development")
.hasTag("spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.SvnKitEnvironmentRepository"))
.hasASpanWithNameIgnoreCase("env find", spanAssert -> spanAssert
.hasTag("spring.cloud.config.environment.application", "foo")
.hasASpanWithNameIgnoreCase("env find",
spanAssert -> spanAssert.hasTag("spring.cloud.config.environment.application", "foo")
.hasTag("spring.cloud.config.environment.profile", "development")
.hasTag("spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.PassthruEnvironmentRepository"));
MeterRegistryAssert.then(this.meterRegistry)
.hasTimerWithNameAndTags("spring.cloud.config.environment.find", KeyValues.of(
"spring.cloud.config.environment.application", "foo", "spring.cloud.config.environment.profile",
"development", "spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.SearchPathCompositeEnvironmentRepository"))
.hasTimerWithNameAndTags("spring.cloud.config.environment.find", KeyValues.of(
"spring.cloud.config.environment.application", "foo", "spring.cloud.config.environment.profile",
"development", "spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository"))
.hasTimerWithNameAndTags("spring.cloud.config.environment.find",
KeyValues.of("spring.cloud.config.environment.application", "foo",
"spring.cloud.config.environment.profile", "development",
"spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.SvnKitEnvironmentRepository"))
.hasTimerWithNameAndTags("spring.cloud.config.environment.find",
KeyValues.of("spring.cloud.config.environment.application", "foo",
"spring.cloud.config.environment.profile", "development",
"spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.PassthruEnvironmentRepository"));
.hasTimerWithNameAndTags("spring.cloud.config.environment.find", KeyValues.of(
"spring.cloud.config.environment.application", "foo", "spring.cloud.config.environment.profile",
"development", "spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.SearchPathCompositeEnvironmentRepository"))
.hasTimerWithNameAndTags("spring.cloud.config.environment.find",
KeyValues.of("spring.cloud.config.environment.application", "foo",
"spring.cloud.config.environment.profile", "development",
"spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository"))
.hasTimerWithNameAndTags("spring.cloud.config.environment.find",
KeyValues.of("spring.cloud.config.environment.application", "foo",
"spring.cloud.config.environment.profile", "development",
"spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.SvnKitEnvironmentRepository"))
.hasTimerWithNameAndTags("spring.cloud.config.environment.find",
KeyValues.of("spring.cloud.config.environment.application", "foo",
"spring.cloud.config.environment.profile", "development",
"spring.cloud.config.environment.class",
"org.springframework.cloud.config.server.environment.PassthruEnvironmentRepository"));
}
private List<FinishedSpan> finishedSpans() {

View File

@@ -125,7 +125,7 @@ public class RefreshableConfigServerIntegrationTests {
EnvironmentRepository repository = Mockito.mock(EnvironmentRepository.class);
Environment environment = new Environment("", "");
given(repository.findOne(isA(String.class), isA(String.class), nullable(String.class), isA(Boolean.class)))
.willReturn(environment);
.willReturn(environment);
return repository;
}
@@ -133,7 +133,7 @@ public class RefreshableConfigServerIntegrationTests {
public ResourceRepository resourceRepository() {
ResourceRepository repository = Mockito.mock(ResourceRepository.class);
given(repository.findOne(isA(String.class), isA(String.class), nullable(String.class), isA(String.class)))
.willReturn(new ByteArrayResource("".getBytes()));
.willReturn(new ByteArrayResource("".getBytes()));
return repository;
}

View File

@@ -66,7 +66,7 @@ public class TransportConfigurationIntegrationTests {
@Test
public void propertyBasedTransportCallbackIsConfigured() {
TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository
.getTransportConfigCallback();
.getTransportConfigCallback();
assertThat(transportConfigCallback).isInstanceOf(PropertiesBasedSshTransportConfigCallback.class);
}
@@ -95,7 +95,7 @@ public class TransportConfigurationIntegrationTests {
@Test
public void propertyBasedTransportCallbackIsConfigured() {
TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository
.getTransportConfigCallback();
.getTransportConfigCallback();
assertThat(transportConfigCallback).isInstanceOf(PropertiesBasedSshTransportConfigCallback.class);
}
@@ -132,7 +132,7 @@ public class TransportConfigurationIntegrationTests {
PropertiesBasedSshTransportConfigCallback configCallback = (PropertiesBasedSshTransportConfigCallback) callback;
assertThat(configCallback.getSshUriProperties().getPrivateKey())
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_1);
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_1);
}
}
@@ -154,7 +154,7 @@ public class TransportConfigurationIntegrationTests {
PropertiesBasedSshTransportConfigCallback configCallback = (PropertiesBasedSshTransportConfigCallback) callback;
assertThat(configCallback.getSshUriProperties().getPrivateKey())
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_1);
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_1);
}
}
@@ -181,11 +181,11 @@ public class TransportConfigurationIntegrationTests {
PropertiesBasedSshTransportConfigCallback configCallback = (PropertiesBasedSshTransportConfigCallback) callback;
MultipleJGitEnvironmentProperties sshUriProperties = configCallback.getSshUriProperties();
assertThat(configCallback.getSshUriProperties().getPrivateKey())
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_1);
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_1);
assertThat(sshUriProperties.getRepos().get("repo1")).isNotNull();
assertThat(sshUriProperties.getRepos().get("repo1").getPrivateKey())
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_2);
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_2);
}
}
@@ -208,11 +208,11 @@ public class TransportConfigurationIntegrationTests {
PropertiesBasedSshTransportConfigCallback configCallback = (PropertiesBasedSshTransportConfigCallback) callback;
MultipleJGitEnvironmentProperties sshUriProperties = configCallback.getSshUriProperties();
assertThat(configCallback.getSshUriProperties().getPrivateKey())
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_1);
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_1);
assertThat(sshUriProperties.getRepos().get("repo1")).isNotNull();
assertThat(sshUriProperties.getRepos().get("repo1").getPrivateKey())
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_2);
.isEqualTo(TestProperties.TEST_PRIVATE_KEY_2);
}
}
@@ -234,7 +234,7 @@ public class TransportConfigurationIntegrationTests {
@Test
public void fileBasedTransportCallbackIsConfigured() {
TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository
.getTransportConfigCallback();
.getTransportConfigCallback();
assertThat(transportConfigCallback).isInstanceOf(FileBasedSshTransportConfigCallback.class);
}
@@ -261,15 +261,15 @@ public class TransportConfigurationIntegrationTests {
// configuration, so we'll reflect
// the createSshConfigStore method to allow us to check that the config
// property is set as expected.
Method createSshConfigStore = factory.getClass().getDeclaredMethod("createSshConfigStore", File.class,
File.class, String.class);
Method createSshConfigStore = factory.getClass()
.getDeclaredMethod("createSshConfigStore", File.class, File.class, String.class);
createSshConfigStore.setAccessible(true);
SshConfigStore configStore = (SshConfigStore) createSshConfigStore.invoke(factory, new File("."),
new File("."), "local-username");
createSshConfigStore.setAccessible(false);
assertThat("yes"
.equals(configStore.lookup("gitserver.com", 22, "username").getValue("StrictHostKeyChecking")))
.isTrue();
.equals(configStore.lookup("gitserver.com", 22, "username").getValue("StrictHostKeyChecking")))
.isTrue();
}
}
@@ -288,7 +288,7 @@ public class TransportConfigurationIntegrationTests {
@Test
public void fileBasedTransportCallbackIsConfigured() {
TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository
.getTransportConfigCallback();
.getTransportConfigCallback();
assertThat(transportConfigCallback).isInstanceOf(FileBasedSshTransportConfigCallback.class);
}
@@ -315,15 +315,15 @@ public class TransportConfigurationIntegrationTests {
// configuration, so we'll reflect
// the createSshConfigStore method to allow us to check that the config
// property is set as expected.
Method createSshConfigStore = factory.getClass().getDeclaredMethod("createSshConfigStore", File.class,
File.class, String.class);
Method createSshConfigStore = factory.getClass()
.getDeclaredMethod("createSshConfigStore", File.class, File.class, String.class);
createSshConfigStore.setAccessible(true);
SshConfigStore configStore = (SshConfigStore) createSshConfigStore.invoke(factory, new File("."),
new File("."), "local-username");
createSshConfigStore.setAccessible(false);
assertThat("yes"
.equals(configStore.lookup("gitserver.com", 22, "username").getValue("StrictHostKeyChecking")))
.isTrue();
.equals(configStore.lookup("gitserver.com", 22, "username").getValue("StrictHostKeyChecking")))
.isTrue();
}
}
@@ -344,7 +344,7 @@ public class TransportConfigurationIntegrationTests {
@Test
public void sshTransportCallbackIsConfigured() {
TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository
.getTransportConfigCallback();
.getTransportConfigCallback();
assertThat(transportConfigCallback).isNotNull();
}
@@ -374,7 +374,7 @@ public class TransportConfigurationIntegrationTests {
@Test
public void sshTransportCallbackIsConfigured() {
TransportConfigCallback transportConfigCallback = this.jGitEnvironmentRepository
.getTransportConfigCallback();
.getTransportConfigCallback();
assertThat(transportConfigCallback).isNotNull();
}

View File

@@ -73,7 +73,7 @@ public class VanillaConfigServerIntegrationTests {
@Test
public void resourseEndpointsWork() {
String text = new TestRestTemplate()
.getForObject("http://localhost:" + this.port + "/foo/development/master/bar.properties", String.class);
.getForObject("http://localhost:" + this.port + "/foo/development/master/bar.properties", String.class);
String expected = "foo: bar";
assertThat(text).as("invalid content").isEqualTo(expected);

View File

@@ -54,40 +54,45 @@ class CompositeEnvironmentBeanFactoryInitializationAotProcessorTests {
SvnKitEnvironmentProperties.class, MultipleJGitEnvironmentRepositoryFactory.class,
SvnEnvironmentRepositoryFactory.class, MultipleJGitEnvironmentProperties.class);
new WebApplicationContextRunner(AnnotationConfigServletWebApplicationContext::new)
.withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.cloud.refresh.enabled=false",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[1].type:svn", "spring.profiles.active:test,composite")
.prepare(context -> {
TestGenerationContext generationContext = new TestGenerationContext(TestTarget.class);
ClassName className = new ApplicationContextAotGenerator().processAheadOfTime(
(GenericApplicationContext) context.getSourceApplicationContext(), generationContext);
generationContext.writeGeneratedContent();
Optional<String> source = getGeneratedSource(generationContext, className.simpleName());
assertThat(source).isNotEmpty();
assertThat(source.get()).contains(
"beanFactory.registerBeanDefinition(\"git-env-repo-properties0\", propertiesDefinition0);",
"beanFactory.registerBeanDefinition(\"git-env-repo0\", repoBeanDefinition0);",
"beanFactory.registerBeanDefinition(\"svn-env-repo-properties1\", propertiesDefinition1);",
"beanFactory.registerBeanDefinition(\"svn-env-repo1\", repoBeanDefinition1);");
ReflectionHints hints = generationContext.getRuntimeHints().reflection();
hintClasses.forEach(clazz -> assertThat(hints.getTypeHint(clazz)).isNotNull());
});
.withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.cloud.refresh.enabled=false",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[1].type:svn", "spring.profiles.active:test,composite")
.prepare(context -> {
TestGenerationContext generationContext = new TestGenerationContext(TestTarget.class);
ClassName className = new ApplicationContextAotGenerator().processAheadOfTime(
(GenericApplicationContext) context.getSourceApplicationContext(), generationContext);
generationContext.writeGeneratedContent();
Optional<String> source = getGeneratedSource(generationContext, className.simpleName());
assertThat(source).isNotEmpty();
assertThat(source.get()).contains(
"beanFactory.registerBeanDefinition(\"git-env-repo-properties0\", propertiesDefinition0);",
"beanFactory.registerBeanDefinition(\"git-env-repo0\", repoBeanDefinition0);",
"beanFactory.registerBeanDefinition(\"svn-env-repo-properties1\", propertiesDefinition1);",
"beanFactory.registerBeanDefinition(\"svn-env-repo1\", repoBeanDefinition1);");
ReflectionHints hints = generationContext.getRuntimeHints().reflection();
hintClasses.forEach(clazz -> assertThat(hints.getTypeHint(clazz)).isNotNull());
});
}
private static Optional<String> getGeneratedSource(TestGenerationContext generationContext,
String simpleClassName) {
return generationContext.getGeneratedFiles().getGeneratedFiles(GeneratedFiles.Kind.SOURCE).values().stream()
.map(inputStreamSource -> {
try {
return new String(inputStreamSource.getInputStream().readAllBytes(), Charset.defaultCharset());
}
catch (IOException e) {
throw new RuntimeException(e);
}
}).filter(source -> source.contains(simpleClassName)).findAny();
return generationContext.getGeneratedFiles()
.getGeneratedFiles(GeneratedFiles.Kind.SOURCE)
.values()
.stream()
.map(inputStreamSource -> {
try {
return new String(inputStreamSource.getInputStream().readAllBytes(), Charset.defaultCharset());
}
catch (IOException e) {
throw new RuntimeException(e);
}
})
.filter(source -> source.contains(simpleClassName))
.findAny();
}
static class TestTarget {

View File

@@ -34,31 +34,31 @@ public class CompositUtilsTests {
@Test
public void getCompositeTypeListWorks() {
new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.profiles.active:test,composite", "spring.config.name:compositeconfigserver",
"spring.jmx.enabled=false",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[1].type:svn")
.run(context -> {
List<String> types = CompositeUtils.getCompositeTypeList(context.getEnvironment());
assertThat(types).containsExactly("git", "svn");
});
.withPropertyValues("spring.profiles.active:test,composite", "spring.config.name:compositeconfigserver",
"spring.jmx.enabled=false",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[1].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[1].type:svn")
.run(context -> {
List<String> types = CompositeUtils.getCompositeTypeList(context.getEnvironment());
assertThat(types).containsExactly("git", "svn");
});
}
@Test
public void getCompositeTypeListFails() {
Assertions.assertThatThrownBy(() -> {
new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class)
.withPropertyValues("spring.profiles.active:test,composite",
"spring.config.name:compositeconfigserver", "spring.jmx.enabled=false",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[2].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[2].type:svn")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
.withPropertyValues("spring.profiles.active:test,composite", "spring.config.name:compositeconfigserver",
"spring.jmx.enabled=false",
"spring.cloud.config.server.composite[0].uri:file:./target/repos/config-repo",
"spring.cloud.config.server.composite[0].type:git",
"spring.cloud.config.server.composite[2].uri:file:///./target/repos/svn-config-repo",
"spring.cloud.config.server.composite[2].type:svn")
.run(context -> {
CompositeUtils.getCompositeTypeList(context.getEnvironment());
});
}).isInstanceOf(IllegalStateException.class);
}

View File

@@ -59,14 +59,14 @@ public class ConfigServerHealthIndicatorTests {
@Test
public void defaultStatusWorks() {
when(this.repository.findOne(anyString(), anyString(), Mockito.<String>isNull(), anyBoolean()))
.thenReturn(this.environment);
.thenReturn(this.environment);
assertThat(this.indicator.health().getStatus()).as("wrong default status").isEqualTo(Status.UP);
}
@Test
public void exceptionStatusIsDownByDefault() {
when(this.repository.findOne(anyString(), anyString(), Mockito.<String>isNull(), anyBoolean()))
.thenThrow(new RuntimeException());
.thenThrow(new RuntimeException());
assertThat(this.indicator.health().getStatus()).as("wrong exception status").isEqualTo(Status.DOWN);
}
@@ -74,7 +74,7 @@ public class ConfigServerHealthIndicatorTests {
public void exceptionDownStatusMayBeCustomized() {
ReflectionTestUtils.setField(this.indicator, "downHealthStatus", "CUSTOM");
when(this.repository.findOne(anyString(), anyString(), Mockito.<String>isNull(), anyBoolean()))
.thenThrow(new RuntimeException());
.thenThrow(new RuntimeException());
assertThat(this.indicator.health().getStatus()).as("wrong exception status").isEqualTo(new Status(("CUSTOM")));
}

Some files were not shown because too many files have changed in this diff Show More