From 2872adf32ec1f82f60d4783987cd0fb0c28a03dd Mon Sep 17 00:00:00 2001 From: buildmaster Date: Tue, 23 Jul 2024 10:34:53 +0000 Subject: [PATCH] Bumping versions --- .../client/ConfigClientAutoConfiguration.java | 26 ++-- .../ConfigClientRequestTemplateFactory.java | 9 +- .../client/ConfigServerConfigDataLoader.java | 8 +- ...onfigServerConfigDataLocationResolver.java | 71 +++++---- .../ConfigServerConfigDataResource.java | 6 +- .../client/ConfigServerHealthIndicator.java | 11 +- .../ConfigServiceBootstrapConfiguration.java | 6 +- .../ConfigServicePropertySourceLocator.java | 3 +- .../config/client/RetryTemplateFactory.java | 9 +- ...figServiceBootstrapConfigurationTests.java | 5 +- .../ConfigClientAutoConfigurationTests.java | 46 +++--- .../ConfigClientConfigDataLoaderTest.java | 8 +- .../client/ConfigClientPropertiesTests.java | 2 +- ...nfigServerBootstrapConfigurationTests.java | 10 +- ...nfigDataCustomizationIntegrationTests.java | 30 ++-- .../ConfigServerConfigDataLoaderTests.java | 71 ++++----- ...ServerConfigDataLocationResolverTests.java | 8 +- ...aMissingEnvironmentPostProcessorTests.java | 2 +- ...verConfigDataNoImportIntegrationTests.java | 26 ++-- .../ConfigServerConfigDataResourceTests.java | 2 +- ...erviceBootstrapConfigurationRetryTest.java | 8 +- ...nfigServicePropertySourceLocatorTests.java | 78 ++++++---- ...ntConfigDataConfigurationNoRetryTests.java | 21 +-- ...eryClientConfigDataConfigurationTests.java | 42 +++--- ...tstrapConfigurationNoSpringRetryTests.java | 5 +- ...figServiceBootstrapConfigurationTests.java | 2 +- .../config/monitor/PropertyPathEndpoint.java | 2 +- ...ropertyPathNotificationExtractorTests.java | 2 +- ...ironmentMonitorAutoConfigurationTests.java | 14 +- .../monitor/PropertyPathEndpointTests.java | 22 +-- .../java/sample/ApplicationFailFastTests.java | 19 +-- ...igDataCustomMediaTypeIntegrationTests.java | 20 +-- .../ConfigDataOrderingIntegrationTests.java | 2 +- ...nfigDataOrderingVaultIntegrationTests.java | 5 +- .../server/ConfigServerApplication.java | 2 +- ...BeanFactoryInitializationAotProcessor.java | 35 ++--- ...teEnvironmentBeanFactoryPostProcessor.java | 9 +- .../server/composite/CompositeUtils.java | 27 ++-- .../composite/OnSearchPathLocatorPresent.java | 4 +- .../server/config/ConfigServerProperties.java | 24 ++-- .../config/ConfigServerRuntimeHints.java | 56 ++++---- .../AbstractCipherResourceEncryptor.java | 4 +- .../CipherEnvironmentEncryptor.java | 6 +- ...wsParameterStoreEnvironmentRepository.java | 17 ++- .../CompositeEnvironmentRepository.java | 8 +- .../CredhubEnvironmentRepository.java | 15 +- .../environment/EnvironmentController.java | 4 +- ...onmentRepositoryPropertySourceLocator.java | 2 +- ...gleSecretManagerEnvironmentRepository.java | 2 +- ...ientConfigurableHttpConnectionFactory.java | 6 +- .../JGitEnvironmentRepository.java | 19 +-- .../MultipleJGitEnvironmentRepository.java | 5 +- ...tipleJGitEnvironmentRepositoryFactory.java | 2 +- .../NativeEnvironmentRepository.java | 9 +- ...servationEnvironmentRepositoryWrapper.java | 8 +- .../SvnKitEnvironmentRepository.java | 5 +- .../GoogleSecretManagerV1AccessStrategy.java | 29 ++-- .../vault/SpringVaultClientConfiguration.java | 11 +- .../AppRoleClientAuthenticationProvider.java | 3 +- .../AwsEc2ClientAuthenticationProvider.java | 11 +- .../AwsIamClientAuthenticationProvider.java | 2 +- .../AzureMsiClientAuthenticationProvider.java | 15 +- ...CubbyholeClientAuthenticationProvider.java | 6 +- .../GcpGceClientAuthenticationProvider.java | 4 +- .../GcpIamClientAuthenticationProvider.java | 4 +- ...ubernetesClientAuthenticationProvider.java | 6 +- .../PcfClientAuthenticationProvider.java | 3 +- .../FileBasedSshTransportConfigCallback.java | 2 +- .../ssh/HostKeyAlgoSupportedValidator.java | 8 +- .../server/ssh/HostKeyAndAlgoBothExist.java | 1 + .../ssh/HostKeyAndAlgoBothExistValidator.java | 20 +-- .../server/ssh/KnownHostsFileValidator.java | 3 +- .../server/ssh/PrivateKeyValidator.java | 18 +-- ...ertiesBasedSshTransportConfigCallback.java | 2 +- .../ssh/PropertyBasedSshSessionFactory.java | 4 +- .../server/ssh/SshPropertyValidator.java | 2 +- .../server/ssh/SshUriPropertyProcessor.java | 4 +- .../AwsCodeCommitCredentialProvider.java | 39 +++-- ...tSkipSslValidationCredentialsProvider.java | 2 +- .../support/GoogleCloudSourceSupport.java | 7 +- .../server/support/HttpClient4Support.java | 9 +- .../server/support/HttpClientSupport.java | 16 ++- .../config/server/AwsS3IntegrationTests.java | 13 +- .../server/CompositeClasspathTests.java | 102 ++++++------- .../server/CompositeIntegrationTests.java | 6 +- ...ackwardsCompatibilityIntegrationTests.java | 2 +- .../ConfigClientOffIntegrationTests.java | 9 +- .../ConfigClientOnIntegrationTests.java | 9 +- .../server/ConfigServerApplicationTests.java | 3 +- ...CompositeConfigServerIntegrationTests.java | 2 +- .../CredhubConfigServerIntegrationTests.java | 2 +- .../config/server/CredhubIntegrationTest.java | 6 +- .../NativeConfigServerIntegrationTests.java | 2 +- .../server/ObservationIntegrationTests.java | 58 ++++---- ...freshableConfigServerIntegrationTests.java | 4 +- ...ransportConfigurationIntegrationTests.java | 40 +++--- .../VanillaConfigServerIntegrationTests.java | 2 +- ...actoryInitializationAotProcessorTests.java | 65 +++++---- .../server/composite/CompositUtilsTests.java | 38 ++--- .../ConfigServerHealthIndicatorTests.java | 6 +- ...omCompositeEnvironmentRepositoryTests.java | 4 +- .../CustomEnvironmentRepositoryTests.java | 2 +- ...vironmentRepositoryConfigurationTests.java | 80 +++++------ ...AwsCodeCommitCredentialsProviderTests.java | 3 +- .../GitCredentialsProviderFactoryTests.java | 3 +- .../CipherEnvironmentEncryptorTests.java | 8 +- .../EncryptionAutoConfigurationTests.java | 32 +++-- ...tionControllerMultiTextEncryptorTests.java | 2 +- .../encryption/EncryptionControllerTests.java | 4 +- .../EnvironmentPrefixHelperTests.java | 2 +- .../vault/VaultEnvironmentEncryptorTests.java | 24 ++-- ...terStoreEnvironmentRepositoryUnitTest.java | 35 +++-- ...ameterStoreEnvironmentRepositoryTests.java | 28 ++-- .../AwsS3EnvironmentRepositoryTests.java | 44 +++--- ...retsManagerEnvironmentRepositoryTests.java | 54 +++---- .../CompositeEnvironmentRepositoryTests.java | 2 +- ...HttpConnectionFactoryIntegrationTests.java | 27 ++-- .../CredhubEnvironmentRepositoryTests.java | 34 ++--- ...EnvironmentControllerIntegrationTests.java | 36 ++--- .../EnvironmentControllerTests.java | 77 +++++----- ...ntEncryptorEnvironmentRepositoryTests.java | 14 +- ...cretManagerEnvironmentRepositoryTests.java | 30 ++-- ...ConfigurableHttpConnectionFactoryTest.java | 83 ++++++----- .../environment/JGitConfigServerTestData.java | 11 +- ...EnvironmentRepositoryConcurrencyTests.java | 5 +- ...EnvironmentRepositoryIntegrationTests.java | 102 ++++++------- .../JGitEnvironmentRepositorySslTests.java | 9 +- .../JGitEnvironmentRepositoryTests.java | 20 +-- ...vironmentRepositoryConfigurationTests.java | 34 ++--- .../JdbcEnvironmentRepositoryTests.java | 27 ++-- ...ApplicationPlaceholderRepositoryTests.java | 8 +- ...mentProfilePlaceholderRepositoryTests.java | 16 +-- ...JGitEnvironmentRepositoryFactoryTests.java | 7 +- ...EnvironmentRepositoryIntegrationTests.java | 41 ++++-- ...ultipleJGitEnvironmentRepositoryTests.java | 59 ++++---- .../NativeEnvironmentRepositoryTests.java | 22 +-- ...tionEnvironmentRepositoryWrapperTests.java | 37 +++-- .../PassthruEnvironmentRepositoryTests.java | 5 +- ...EnvironmentRepositoryIntegrationTests.java | 15 +- .../SVNKitEnvironmentRepositoryTests.java | 3 +- ...EnvironmentRepositoryIntegrationTests.java | 4 +- .../VaultEnvironmentRepositoryTests.java | 136 ++++++++++-------- .../VaultKvAccessStrategyFactoryTest.java | 2 +- .../SpringVaultClientConfigurationTests.java | 16 ++- ...aultEnvironmentRepositoryFactoryTests.java | 6 +- ...SpringVaultEnvironmentRepositoryTests.java | 76 +++++----- ...RoleClientAuthenticationProviderTests.java | 18 +-- .../GenericResourceRepositoryTests.java | 10 +- .../ResourceControllerIntegrationTests.java | 44 +++--- .../resource/ResourceControllerTests.java | 8 +- .../ssh/FileBasedSshSessionFactoryTest.java | 4 +- .../PropertyBasedSshSessionFactoryTest.java | 17 +-- .../server/ssh/SshPropertyValidatorTest.java | 14 +- ...pSslValidationCredentialsProviderTest.java | 70 +++++---- .../support/HttpClient4SupportTest.java | 2 +- .../test/TestConfigServerApplication.java | 2 +- 156 files changed, 1648 insertions(+), 1300 deletions(-) diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientAutoConfiguration.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientAutoConfiguration.java index 1b0688dc..a86efc1d 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientAutoConfiguration.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientAutoConfiguration.java @@ -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)); } } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientRequestTemplateFactory.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientRequestTemplateFactory.java index d304664e..140824b1 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientRequestTemplateFactory.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigClientRequestTemplateFactory.java @@ -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; } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataLoader.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataLoader.java index 8c799161..edd4bc90 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataLoader.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataLoader.java @@ -126,7 +126,7 @@ public class ConfigServerConfigDataLoader implements ConfigDataLoader map = translateOrigins(source.getName(), (Map) source.getSource()); @@ -222,7 +222,7 @@ public class ConfigServerConfigDataLoader implements ConfigDataLoader 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 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; diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataLocationResolver.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataLocationResolver.java index 2bd9ee36..0c9a9020 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataLocationResolver.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataLocationResolver.java @@ -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); }); } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataResource.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataResource.java index 89a312f3..46ca540d 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataResource.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerConfigDataResource.java @@ -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(); } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerHealthIndicator.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerHealthIndicator.java index 4a6bc91c..a1c71c10 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerHealthIndicator.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServerHealthIndicator.java @@ -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; } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfiguration.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfiguration.java index 2bc51c97..ba28b930 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfiguration.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfiguration.java @@ -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(); } } diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocator.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocator.java index fdf91d4a..09b245f6 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocator.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocator.java @@ -91,7 +91,8 @@ public class ConfigServicePropertySourceLocator implements PropertySourceLocator if (environment.getActiveProfiles().length > 0) { List finalCombinedProfiles = combinedProfiles; List 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()) { diff --git a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/RetryTemplateFactory.java b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/RetryTemplateFactory.java index 068ea985..99ac6565 100644 --- a/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/RetryTemplateFactory.java +++ b/spring-cloud-config-client/src/main/java/org/springframework/cloud/config/client/RetryTemplateFactory.java @@ -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); } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/BaseDiscoveryClientConfigServiceBootstrapConfigurationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/BaseDiscoveryClientConfigServiceBootstrapConfigurationTests.java index df1fd00e..2de8e694 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/BaseDiscoveryClientConfigServiceBootstrapConfigurationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/BaseDiscoveryClientConfigServiceBootstrapConfigurationTests.java @@ -66,12 +66,13 @@ public abstract class BaseDiscoveryClientConfigServiceBootstrapConfigurationTest 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 expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup() { assertThat(this.context.getBeanNamesForType(DiscoveryClientConfigServiceBootstrapConfiguration.class).length) - .isEqualTo(1); + .isEqualTo(1); } void expectConfigClientPropertiesHasDefaultConfiguration() { diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientAutoConfigurationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientAutoConfigurationTests.java index 804bc790..a6d919ab 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientAutoConfigurationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientAutoConfigurationTests.java @@ -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(); diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientConfigDataLoaderTest.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientConfigDataLoaderTest.java index f2efdb01..5e3f9ce1 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientConfigDataLoaderTest.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientConfigDataLoaderTest.java @@ -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.any())).thenReturn(responseEntity); + ArgumentMatchers.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.any())).thenReturn(responseEntity); + ArgumentMatchers.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)); diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientPropertiesTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientPropertiesTests.java index 83d0dd98..497da792 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientPropertiesTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigClientPropertiesTests.java @@ -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()); } } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerBootstrapConfigurationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerBootstrapConfigurationTests.java index 3bc06345..342fba5f 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerBootstrapConfigurationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerBootstrapConfigurationTests.java @@ -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(); } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataCustomizationIntegrationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataCustomizationIntegrationTests.java index 62d615d7..a587c3b9 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataCustomizationIntegrationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataCustomizationIntegrationTests.java @@ -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(); } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataLoaderTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataLoaderTests.java index 1ea9f860..fb439239 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataLoaderTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataLoaderTests.java @@ -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 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.>any(), anyString(), - anyString()); + Mockito.verify(this.restTemplate) + .exchange(anyString(), any(HttpMethod.class), httpEntityArgumentCaptor.capture(), + ArgumentMatchers.>any(), anyString(), anyString()); HttpEntity 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 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.any())).thenReturn(responseEntity); + eq(applicationName), ArgumentMatchers.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()); diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataLocationResolverTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataLocationResolverTests.java index b0836f4e..9f2040ee 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataLocationResolverTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataLocationResolverTests.java @@ -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> 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) { diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataMissingEnvironmentPostProcessorTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataMissingEnvironmentPostProcessorTests.java index 3931c54a..ebb89013 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataMissingEnvironmentPostProcessorTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataMissingEnvironmentPostProcessorTests.java @@ -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 diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataNoImportIntegrationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataNoImportIntegrationTests.java index c816688c..625cd9fb 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataNoImportIntegrationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataNoImportIntegrationTests.java @@ -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 } } diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataResourceTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataResourceTests.java index b2d5726c..0839f630 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataResourceTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServerConfigDataResourceTests.java @@ -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, diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfigurationRetryTest.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfigurationRetryTest.java index 80b61971..8a874a5c 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfigurationRetryTest.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServiceBootstrapConfigurationRetryTest.java @@ -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(); diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocatorTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocatorTests.java index 60731cba..b53d80a1 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocatorTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/ConfigServicePropertySourceLocatorTests.java @@ -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 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()); diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigDataConfigurationNoRetryTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigDataConfigurationNoRetryTests.java index 601a1a1e..fc58c455 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigDataConfigurationNoRetryTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigDataConfigurationNoRetryTests.java @@ -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); diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigDataConfigurationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigDataConfigurationTests.java index 35b9b211..07e427e3 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigDataConfigurationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigDataConfigurationTests.java @@ -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() { diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTests.java index c62447d4..eb6d4fbb 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationNoSpringRetryTests.java @@ -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 diff --git a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationTests.java b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationTests.java index fd7eb797..afee1ef6 100644 --- a/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationTests.java +++ b/spring-cloud-config-client/src/test/java/org/springframework/cloud/config/client/DiscoveryClientConfigServiceBootstrapConfigurationTests.java @@ -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 diff --git a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java index b4f0dfa5..03648a9e 100644 --- a/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java +++ b/spring-cloud-config-monitor/src/main/java/org/springframework/cloud/config/monitor/PropertyPathEndpoint.java @@ -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; } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractorTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractorTests.java index 6fae4cd8..c361924f 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractorTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/CompositePropertyPathNotificationExtractorTests.java @@ -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(); diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfigurationTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfigurationTests.java index 7d155458..d7e8ae70 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfigurationTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/EnvironmentMonitorAutoConfigurationTests.java @@ -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(); } diff --git a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/PropertyPathEndpointTests.java b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/PropertyPathEndpointTests.java index 93048af0..ca678f09 100644 --- a/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/PropertyPathEndpointTests.java +++ b/spring-cloud-config-monitor/src/test/java/org/springframework/cloud/config/monitor/PropertyPathEndpointTests.java @@ -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]"); } } diff --git a/spring-cloud-config-sample/src/test/java/sample/ApplicationFailFastTests.java b/spring-cloud-config-sample/src/test/java/sample/ApplicationFailFastTests.java index bd9032e9..6f891f81 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ApplicationFailFastTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ApplicationFailFastTests.java @@ -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"); } diff --git a/spring-cloud-config-sample/src/test/java/sample/ConfigDataCustomMediaTypeIntegrationTests.java b/spring-cloud-config-sample/src/test/java/sample/ConfigDataCustomMediaTypeIntegrationTests.java index b401e31a..8c9d2bf7 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ConfigDataCustomMediaTypeIntegrationTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ConfigDataCustomMediaTypeIntegrationTests.java @@ -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 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 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"); } diff --git a/spring-cloud-config-sample/src/test/java/sample/ConfigDataOrderingIntegrationTests.java b/spring-cloud-config-sample/src/test/java/sample/ConfigDataOrderingIntegrationTests.java index 0f973c8d..f6eec6fe 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ConfigDataOrderingIntegrationTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ConfigDataOrderingIntegrationTests.java @@ -75,7 +75,7 @@ public class ConfigDataOrderingIntegrationTests { @SuppressWarnings({ "unchecked", "rawtypes" }) public void contextLoads() { ResponseEntity 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"); diff --git a/spring-cloud-config-sample/src/test/java/sample/ConfigDataOrderingVaultIntegrationTests.java b/spring-cloud-config-sample/src/test/java/sample/ConfigDataOrderingVaultIntegrationTests.java index 7d5f104a..408c55b9 100644 --- a/spring-cloud-config-sample/src/test/java/sample/ConfigDataOrderingVaultIntegrationTests.java +++ b/spring-cloud-config-sample/src/test/java/sample/ConfigDataOrderingVaultIntegrationTests.java @@ -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 { diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ConfigServerApplication.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ConfigServerApplication.java index f4a73fed..80df01ed 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ConfigServerApplication.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ConfigServerApplication.java @@ -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); } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/aot/CompositeEnvironmentBeanFactoryInitializationAotProcessor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/aot/CompositeEnvironmentBeanFactoryInitializationAotProcessor.java index 4983e57c..d0ae84b7 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/aot/CompositeEnvironmentBeanFactoryInitializationAotProcessor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/aot/CompositeEnvironmentBeanFactoryInitializationAotProcessor.java @@ -79,16 +79,19 @@ public class CompositeEnvironmentBeanFactoryInitializationAotProcessor private static Map 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> factoryClass = (Class>) CompositeUtils - .getFactoryClass(beanFactory, factoryName); + .getFactoryClass(beanFactory, factoryName); Type[] environmentRepositoryFactoryTypeParams = CompositeUtils - .getEnvironmentRepositoryFactoryTypeParams(factoryClass); + .getEnvironmentRepositoryFactoryTypeParams(factoryClass); Class repoClass = (Class) environmentRepositoryFactoryTypeParams[0]; Class propertiesClass = (Class) 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); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeEnvironmentBeanFactoryPostProcessor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeEnvironmentBeanFactoryPostProcessor.java index 61fddbf7..f5aa4955 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeEnvironmentBeanFactoryPostProcessor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeEnvironmentBeanFactoryPostProcessor.java @@ -60,13 +60,16 @@ public class CompositeEnvironmentBeanFactoryPostProcessor implements BeanFactory propertiesClass = (Class) 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); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeUtils.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeUtils.java index c4721e9f..90f13dca 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeUtils.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/CompositeUtils.java @@ -51,8 +51,13 @@ public final class CompositeUtils { * @return list of matching types */ public static List 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 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(); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/OnSearchPathLocatorPresent.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/OnSearchPathLocatorPresent.java index 6aa6f805..f8d2d0fd 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/OnSearchPathLocatorPresent.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/composite/OnSearchPathLocatorPresent.java @@ -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(); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerProperties.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerProperties.java index 118ddf58..94a8c9bf 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerProperties.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerProperties.java @@ -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(); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerRuntimeHints.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerRuntimeHints.java index 90173142..a6127ead 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerRuntimeHints.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/config/ConfigServerRuntimeHints.java @@ -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)); } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/AbstractCipherResourceEncryptor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/AbstractCipherResourceEncryptor.java index d1eca924..7cc21a15 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/AbstractCipherResourceEncryptor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/AbstractCipherResourceEncryptor.java @@ -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)); } } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptor.java index 15af51d3..fedc75c7 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptor.java @@ -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 = ""; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/AwsParameterStoreEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/AwsParameterStoreEnvironmentRepository.java index 9510d4dc..9d93f37b 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/AwsParameterStoreEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/AwsParameterStoreEnvironmentRepository.java @@ -93,8 +93,10 @@ public class AwsParameterStoreEnvironmentRepository implements EnvironmentReposi List reversedProfiles = new ArrayList<>(Arrays.asList(profiles)); Collections.reverse(reversedProfiles); - List orderedProfiles = Stream.concat(reversedProfiles.stream().filter(p -> !p.equals(defaultProfile)), - Arrays.stream(new String[] { defaultProfile })).collect(Collectors.toList()); + List 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 getPropertiesByParameterPath(String path) { Map 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); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java index 01802a3d..3933b92e 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepository.java @@ -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()); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepository.java index 3e0d9335..8c6b1bee 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepository.java @@ -94,12 +94,15 @@ public class CredhubEnvironmentRepository implements EnvironmentRepository, Orde private Map 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 diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java index e8766a3b..bb8019ee 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentController.java @@ -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 diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryPropertySourceLocator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryPropertySourceLocator.java index 2274f7d2..f4263a25 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryPropertySourceLocator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/EnvironmentRepositoryPropertySourceLocator.java @@ -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 map = (Map) source.getSource(); composite.addPropertySource(new MapPropertySource(source.getName(), map)); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/GoogleSecretManagerEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/GoogleSecretManagerEnvironmentRepository.java index b8232d21..cf535201 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/GoogleSecretManagerEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/GoogleSecretManagerEnvironmentRepository.java @@ -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()) { diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactory.java index e3999444..69a1c728 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactory.java @@ -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 keys = builderMap.keySet().stream().filter(key -> !PLACEHOLDER_PATTERN.matcher(key).find()) - .collect(Collectors.toList()); + List keys = builderMap.keySet() + .stream() + .filter(key -> !PLACEHOLDER_PATTERN.matcher(key).find()) + .collect(Collectors.toList()); if (keys.size() == 1) { return builderMap.get(keys.get(0)); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java index 49d1ae9f..77fc7f4c 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepository.java @@ -446,10 +446,10 @@ public class JGitEnvironmentRepository extends AbstractScmEnvironmentRepository private List deleteBranches(Git git, Collection 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 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 { diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepository.java index dac3c161..4ef966a6 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepository.java @@ -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 diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactory.java index 157f0bfa..9245f9a9 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactory.java @@ -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; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepository.java index ff595aec..6d3d168b 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepository.java @@ -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; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ObservationEnvironmentRepositoryWrapper.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ObservationEnvironmentRepositoryWrapper.java index 4f139d2f..dfd991bf 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ObservationEnvironmentRepositoryWrapper.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/ObservationEnvironmentRepositoryWrapper.java @@ -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)); } /** diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentRepository.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentRepository.java index 19a5c579..cb2ed216 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentRepository.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/SvnKitEnvironmentRepository.java @@ -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; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/secretmanager/GoogleSecretManagerV1AccessStrategy.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/secretmanager/GoogleSecretManagerV1AccessStrategy.java index 57a94b21..8e346e47 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/secretmanager/GoogleSecretManagerV1AccessStrategy.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/secretmanager/GoogleSecretManagerV1AccessStrategy.java @@ -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 result = new ArrayList(); 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 result = new ArrayList(); 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 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 entity = new HttpEntity("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; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/SpringVaultClientConfiguration.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/SpringVaultClientConfiguration.java index 120ee446..0eee4427 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/SpringVaultClientConfiguration.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/SpringVaultClientConfiguration.java @@ -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, diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AppRoleClientAuthenticationProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AppRoleClientAuthenticationProvider.java index 17bf9717..30de2af2 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AppRoleClientAuthenticationProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AppRoleClientAuthenticationProvider.java @@ -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()); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AwsEc2ClientAuthenticationProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AwsEc2ClientAuthenticationProvider.java index ada2b6c1..21b6ee53 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AwsEc2ClientAuthenticationProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AwsEc2ClientAuthenticationProvider.java @@ -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); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AwsIamClientAuthenticationProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AwsIamClientAuthenticationProvider.java index 22a2ec70..116498a7 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AwsIamClientAuthenticationProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AwsIamClientAuthenticationProvider.java @@ -63,7 +63,7 @@ public class AwsIamClientAuthenticationProvider extends SpringVaultClientAuthent } builder.path(awsIam.getAwsPath()) // - .credentialsProvider(credentialsProvider); + .credentialsProvider(credentialsProvider); AwsIamAuthenticationOptions options = builder.credentialsProvider(credentialsProvider).build(); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AzureMsiClientAuthenticationProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AzureMsiClientAuthenticationProvider.java index a4c6c041..5369854a 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AzureMsiClientAuthenticationProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/AzureMsiClientAuthenticationProvider.java @@ -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); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/CubbyholeClientAuthenticationProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/CubbyholeClientAuthenticationProvider.java index f0402210..01dd3d01 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/CubbyholeClientAuthenticationProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/CubbyholeClientAuthenticationProvider.java @@ -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); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/GcpGceClientAuthenticationProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/GcpGceClientAuthenticationProvider.java index 2377129f..0a31f4a7 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/GcpGceClientAuthenticationProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/GcpGceClientAuthenticationProvider.java @@ -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()); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/GcpIamClientAuthenticationProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/GcpIamClientAuthenticationProvider.java index 84c5b3ba..9d1b0a38 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/GcpIamClientAuthenticationProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/GcpIamClientAuthenticationProvider.java @@ -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()); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/KubernetesClientAuthenticationProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/KubernetesClientAuthenticationProvider.java index 3ff4c6d7..65667e52 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/KubernetesClientAuthenticationProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/KubernetesClientAuthenticationProvider.java @@ -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); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/PcfClientAuthenticationProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/PcfClientAuthenticationProvider.java index 5c8f49b3..50d5cefb 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/PcfClientAuthenticationProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/environment/vault/authentication/PcfClientAuthenticationProvider.java @@ -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())); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/FileBasedSshTransportConfigCallback.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/FileBasedSshTransportConfigCallback.java index 70db0596..b89ea77a 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/FileBasedSshTransportConfigCallback.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/FileBasedSshTransportConfigCallback.java @@ -40,7 +40,7 @@ public class FileBasedSshTransportConfigCallback implements TransportConfigCallb public FileBasedSshTransportConfigCallback(MultipleJGitEnvironmentProperties sshUriProperties) { this.sshUriProperties = sshUriProperties; Map sshKeysByHostname = new SshUriPropertyProcessor(this.sshUriProperties) - .getSshKeysByHostname(); + .getSshKeysByHostname(); if (sshKeysByHostname.isEmpty()) { this.sshdSessionFactory = null; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupportedValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupportedValidator.java index 32780dc5..017d373a 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupportedValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAlgoSupportedValidator.java @@ -63,7 +63,7 @@ public class HostKeyAlgoSupportedValidator context.disableDefaultConstraintViolation(); Set validationResults = new HashSet<>(); List 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; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExist.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExist.java index be088862..8459c224 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExist.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExist.java @@ -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) diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExistValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExistValidator.java index ed3b662e..98729a2b 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExistValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/HostKeyAndAlgoBothExistValidator.java @@ -58,7 +58,7 @@ public class HostKeyAndAlgoBothExistValidator public boolean isValid(MultipleJGitEnvironmentProperties sshUriProperties, ConstraintValidatorContext context) { Set validationResults = new HashSet<>(); List 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; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileValidator.java index 7262698c..8333a23b 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/KnownHostsFileValidator.java @@ -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; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyValidator.java index ccc1fc2f..2486fcb0 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PrivateKeyValidator.java @@ -57,7 +57,7 @@ public class PrivateKeyValidator implements ConstraintValidator validationResults = new HashSet<>(); List 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 sshKeysByHostname = new SshUriPropertyProcessor(this.sshUriProperties) - .getSshKeysByHostname(); + .getSshKeysByHostname(); if (sshKeysByHostname.isEmpty()) { this.sshdSessionFactory = null; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactory.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactory.java index edec05d1..63d03a13 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactory.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactory.java @@ -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; diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshPropertyValidator.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshPropertyValidator.java index 1e68dbfa..235069fd 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshPropertyValidator.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshPropertyValidator.java @@ -64,7 +64,7 @@ public class SshPropertyValidator { List allRepoProperties = new ArrayList<>(); allRepoProperties.add(sshUriProperties); Map repos = sshUriProperties - .getRepos(); + .getRepos(); if (repos != null) { allRepoProperties.addAll(repos.values()); } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessor.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessor.java index 04dc7788..07c56c7c 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessor.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/ssh/SshUriPropertyProcessor.java @@ -64,10 +64,10 @@ public class SshUriPropertyProcessor { sshUriPropertyMap.put(getHostname(parentUri), uriProperties); } Map 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); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java index 304b762c..f696d61a 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/AwsCodeCommitCredentialProvider.java @@ -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); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProvider.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProvider.java index 1f6bc974..a774cc22 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProvider.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProvider.java @@ -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; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GoogleCloudSourceSupport.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GoogleCloudSourceSupport.java index 3f18a961..ac00724b 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GoogleCloudSourceSupport.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/GoogleCloudSourceSupport.java @@ -119,8 +119,11 @@ public final class GoogleCloudSourceSupport { @Override public Map 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); diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClient4Support.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClient4Support.java index f0817154..3571ce35 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClient4Support.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClient4Support.java @@ -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; } diff --git a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClientSupport.java b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClientSupport.java index 7644add8..c088991a 100644 --- a/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClientSupport.java +++ b/spring-cloud-config-server/src/main/java/org/springframework/cloud/config/server/support/HttpClientSupport.java @@ -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()); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/AwsS3IntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/AwsS3IntegrationTests.java index 35e9bf33..da5e0ad1 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/AwsS3IntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/AwsS3IntegrationTests.java @@ -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 diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeClasspathTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeClasspathTests.java index fc248f34..6deda1f9 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeClasspathTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeClasspathTests.java @@ -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()); + }); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java index ccfa3c43..660751a9 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CompositeIntegrationTests.java @@ -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); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientBackwardsCompatibilityIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientBackwardsCompatibilityIntegrationTests.java index 14d04d28..88f5dafe 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientBackwardsCompatibilityIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientBackwardsCompatibilityIntegrationTests.java @@ -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"); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOffIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOffIntegrationTests.java index d1805946..6d6e3d68 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOffIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOffIntegrationTests.java @@ -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; } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java index 633b3391..6e9512e7 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigClientOnIntegrationTests.java @@ -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; } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigServerApplicationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigServerApplicationTests.java index f9e01cb6..9e5792a6 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigServerApplicationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ConfigServerApplicationTests.java @@ -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 } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java index 3d94219d..785aa3a9 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubCompositeConfigServerIntegrationTests.java @@ -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"); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java index 3ad3fc3e..16d84af3 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubConfigServerIntegrationTests.java @@ -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"); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubIntegrationTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubIntegrationTest.java index 895bd526..3c57d96d 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubIntegrationTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/CredhubIntegrationTest.java @@ -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); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java index eeadd43a..5f37685c 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/NativeConfigServerIntegrationTests.java @@ -80,7 +80,7 @@ public class NativeConfigServerIntegrationTests { @Test public void badYaml() { ResponseEntity 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); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ObservationIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ObservationIntegrationTests.java index 052bcd74..3ed166bc 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ObservationIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ObservationIntegrationTests.java @@ -91,46 +91,48 @@ class ObservationIntegrationTests { List 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 finishedSpans() { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/RefreshableConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/RefreshableConfigServerIntegrationTests.java index b5ca28ba..32e80d13 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/RefreshableConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/RefreshableConfigServerIntegrationTests.java @@ -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; } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java index 9b1436a9..72e48eec 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/TransportConfigurationIntegrationTests.java @@ -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(); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java index b981a700..11edc671 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/VanillaConfigServerIntegrationTests.java @@ -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); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/aot/CompositeEnvironmentBeanFactoryInitializationAotProcessorTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/aot/CompositeEnvironmentBeanFactoryInitializationAotProcessorTests.java index 7e8e820b..feba5510 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/aot/CompositeEnvironmentBeanFactoryInitializationAotProcessorTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/aot/CompositeEnvironmentBeanFactoryInitializationAotProcessorTests.java @@ -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 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 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 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 { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/composite/CompositUtilsTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/composite/CompositUtilsTests.java index ad56246b..be69e4e3 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/composite/CompositUtilsTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/composite/CompositUtilsTests.java @@ -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 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 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); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicatorTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicatorTests.java index 43ec7114..a087c967 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicatorTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/ConfigServerHealthIndicatorTests.java @@ -59,14 +59,14 @@ public class ConfigServerHealthIndicatorTests { @Test public void defaultStatusWorks() { when(this.repository.findOne(anyString(), anyString(), Mockito.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.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.isNull(), anyBoolean())) - .thenThrow(new RuntimeException()); + .thenThrow(new RuntimeException()); assertThat(this.indicator.health().getStatus()).as("wrong exception status").isEqualTo(new Status(("CUSTOM"))); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java index ef416e23..8a5dfeda 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomCompositeEnvironmentRepositoryTests.java @@ -73,7 +73,7 @@ public class CustomCompositeEnvironmentRepositoryTests { @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); List propertySources = environment.getPropertySources(); assertThat(3).isEqualTo(propertySources.size()); assertThat("overrides").isEqualTo(propertySources.get(0).getName()); @@ -124,7 +124,7 @@ public class CustomCompositeEnvironmentRepositoryTests { @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); List propertySources = environment.getPropertySources(); assertThat(3).isEqualTo(propertySources.size()); assertThat("overrides").isEqualTo(propertySources.get(0).getName()); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java index faba9234..44b1bfff 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/CustomEnvironmentRepositoryTests.java @@ -51,7 +51,7 @@ public class CustomEnvironmentRepositoryTests { @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()).isNotEmpty(); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfigurationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfigurationTests.java index 946140c1..bbba3cbd 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfigurationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/config/EnvironmentRepositoryConfigurationTests.java @@ -39,62 +39,60 @@ public class EnvironmentRepositoryConfigurationTests { @Test public void configTokenProviderCanBeOverridden() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EnvironmentRepositoryConfiguration.class, TestBeans.class)) - .withPropertyValues("spring.profiles.active=composite", - "spring.cloud.config.server.vault.authentication=TOKEN", - "spring.cloud.config.server.vault.token=testTokenValue", - "spring.cloud.config.server.composite[0].type=vault", - "spring.cloud.config.server.composite[1].type=git", - "spring.cloud.config.server.composite[1].uri=https://test.com/Some-Test-Repo.git") - .run((context) -> { - assertThat(context.getBean(ConfigTokenProvider.class)).isNotNull(); - assertThat(context.getBean(ConfigTokenProvider.class)) - .isInstanceOf(EnvironmentConfigTokenProvider.class); - EnvironmentConfigTokenProvider tokenProvider = context - .getBean(EnvironmentConfigTokenProvider.class); - assertThat(tokenProvider.getToken()).isEqualTo("testTokenValue"); - }); + .withConfiguration(AutoConfigurations.of(EnvironmentRepositoryConfiguration.class, TestBeans.class)) + .withPropertyValues("spring.profiles.active=composite", + "spring.cloud.config.server.vault.authentication=TOKEN", + "spring.cloud.config.server.vault.token=testTokenValue", + "spring.cloud.config.server.composite[0].type=vault", + "spring.cloud.config.server.composite[1].type=git", + "spring.cloud.config.server.composite[1].uri=https://test.com/Some-Test-Repo.git") + .run((context) -> { + assertThat(context.getBean(ConfigTokenProvider.class)).isNotNull(); + assertThat(context.getBean(ConfigTokenProvider.class)) + .isInstanceOf(EnvironmentConfigTokenProvider.class); + EnvironmentConfigTokenProvider tokenProvider = context.getBean(EnvironmentConfigTokenProvider.class); + assertThat(tokenProvider.getToken()).isEqualTo("testTokenValue"); + }); } @Test public void awsParamStoreFactoryBeanExistsWithComposite() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EnvironmentRepositoryConfiguration.class, TestBeans.class)) - .withPropertyValues("spring.profiles.active=composite", - "spring.cloud.config.server.composite[0].type=awsparamstore", - "spring.cloud.config.server.composite[0].region=us-east-1", - "spring.cloud.config.server.composite[1].type=git", - "spring.cloud.config.server.composite[1].uri=https://test.com/Some-Test-Repo.git") - .run((context) -> { - assertThat(context.getBean(AwsParameterStoreEnvironmentRepositoryFactory.class)).isNotNull(); - }); + .withConfiguration(AutoConfigurations.of(EnvironmentRepositoryConfiguration.class, TestBeans.class)) + .withPropertyValues("spring.profiles.active=composite", + "spring.cloud.config.server.composite[0].type=awsparamstore", + "spring.cloud.config.server.composite[0].region=us-east-1", + "spring.cloud.config.server.composite[1].type=git", + "spring.cloud.config.server.composite[1].uri=https://test.com/Some-Test-Repo.git") + .run((context) -> { + assertThat(context.getBean(AwsParameterStoreEnvironmentRepositoryFactory.class)).isNotNull(); + }); } @Test public void customGitCredentialsProvider() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(GitTestBeans.class, TestBeans.class, - EnvironmentRepositoryConfiguration.class)) - .withPropertyValues("spring.profiles.active=git", - "spring.cloud.config.server.git.uri=http://github.com/user/test") - .run((context) -> { - assertThat(context.getBean(GitCredentialsProviderFactory.class)) - .isInstanceOf(GitTestBeans.CustomGitCredentialsProviderFactory.class); - }); + .withConfiguration(AutoConfigurations.of(GitTestBeans.class, TestBeans.class, + EnvironmentRepositoryConfiguration.class)) + .withPropertyValues("spring.profiles.active=git", + "spring.cloud.config.server.git.uri=http://github.com/user/test") + .run((context) -> { + assertThat(context.getBean(GitCredentialsProviderFactory.class)) + .isInstanceOf(GitTestBeans.CustomGitCredentialsProviderFactory.class); + }); } @Test public void configServerActuatorConfigurationWithCustomHealthStatus() { new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of( - EnvironmentRepositoryConfigurationTests.EnableConfigurationPropertiesBeans.class, - EnvironmentRepositoryConfiguration.ConfigServerActuatorConfiguration.class)) - .withPropertyValues("spring.cloud.config.server.health.down-health-status=CUSTOMIZED") - .run((context) -> { - ConfigServerHealthIndicator healthIndicator = context.getBean(ConfigServerHealthIndicator.class); - assertThat(ReflectionTestUtils.getField(healthIndicator, "downHealthStatus")) - .isEqualTo("CUSTOMIZED"); - }); + .withConfiguration(AutoConfigurations.of( + EnvironmentRepositoryConfigurationTests.EnableConfigurationPropertiesBeans.class, + EnvironmentRepositoryConfiguration.ConfigServerActuatorConfiguration.class)) + .withPropertyValues("spring.cloud.config.server.health.down-health-status=CUSTOMIZED") + .run((context) -> { + ConfigServerHealthIndicator healthIndicator = context.getBean(ConfigServerHealthIndicator.class); + assertThat(ReflectionTestUtils.getField(healthIndicator, "downHealthStatus")).isEqualTo("CUSTOMIZED"); + }); } @TestConfiguration diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java index c6f90d9b..01746715 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/AwsCodeCommitCredentialsProviderTests.java @@ -70,8 +70,7 @@ public class AwsCodeCommitCredentialsProviderTests { @Test public void testSupportsUsernamePassword() { assertThat(this.provider - .supports(new CredentialItem[] { new CredentialItem.Username(), new CredentialItem.Password() })) - .isTrue(); + .supports(new CredentialItem[] { new CredentialItem.Username(), new CredentialItem.Password() })).isTrue(); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/GitCredentialsProviderFactoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/GitCredentialsProviderFactoryTests.java index a7a72e5d..4c7879d0 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/GitCredentialsProviderFactoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/credentials/GitCredentialsProviderFactoryTests.java @@ -98,7 +98,8 @@ public class GitCredentialsProviderFactoryTests { CredentialsProvider provider = this.factory.createFor(HTTPS_GIT_REPO, USER, PASSWORD, null); assertThat(provider).isNotNull(); assertThat(provider instanceof UsernamePasswordCredentialsProvider) - .as("deprecated createFor() should not enable ssl validation skipping").isTrue(); + .as("deprecated createFor() should not enable ssl validation skipping") + .isTrue(); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptorTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptorTests.java index 67886ad7..71fb02fc 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptorTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/CipherEnvironmentEncryptorTests.java @@ -63,7 +63,7 @@ public class CipherEnvironmentEncryptorTests { // then assertThat(encryptor.decrypt(environment).getPropertySources().get(0).getSource().get(environment.getName())) - .isEqualTo(secret); + .isEqualTo(secret); } @ParameterizedTest @@ -83,7 +83,7 @@ public class CipherEnvironmentEncryptorTests { // then assertThat(encryptor.decrypt(environment).getPropertySources().get(0).getSource().get(environment.getName())) - .isEqualTo(secret); + .isEqualTo(secret); } @ParameterizedTest @@ -97,7 +97,7 @@ public class CipherEnvironmentEncryptorTests { // then assertThat(encryptor.decrypt(environment).getPropertySources().get(0).getSource().get(environment.getName())) - .isEqualTo(null); + .isEqualTo(null); } @ParameterizedTest @@ -116,7 +116,7 @@ public class CipherEnvironmentEncryptorTests { // then assertThat(encryptor.decrypt(environment).getPropertySources().get(0).getSource().get(environment.getName())) - .isEqualTo(secret); + .isEqualTo(secret); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionAutoConfigurationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionAutoConfigurationTests.java index 00174a56..87e1b900 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionAutoConfigurationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionAutoConfigurationTests.java @@ -42,7 +42,9 @@ public class EncryptionAutoConfigurationTests { ConfigurableApplicationContext context = new SpringApplicationBuilder( DefaultTextEncryptionAutoConfiguration.class, RsaEncryptionAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class, - PropertyPlaceholderAutoConfiguration.class).properties("server.port=0").run(); + PropertyPlaceholderAutoConfiguration.class) + .properties("server.port=0") + .run(); TextEncryptor textEncryptor = context.getBean(TextEncryptor.class); String[] textEncryptorLocatorNames = context.getBeanNamesForType(TextEncryptorLocator.class); assertThat(textEncryptor).isInstanceOf(TextEncryptorUtils.FailsafeTextEncryptor.class); @@ -56,9 +58,9 @@ public class EncryptionAutoConfigurationTests { DefaultTextEncryptionAutoConfiguration.class, RsaEncryptionAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class, PropertyPlaceholderAutoConfiguration.class) - .properties("server.port=0", "encrypt.key-store.location=classpath:server.jks", - "encrypt.key-store.password=letmein", "encrypt.key-store.alias=myKey") - .run(); + .properties("server.port=0", "encrypt.key-store.location=classpath:server.jks", + "encrypt.key-store.password=letmein", "encrypt.key-store.alias=myKey") + .run(); TextEncryptor textEncryptor = context.getBean(TextEncryptor.class); TextEncryptorLocator textEncryptorLocator = context.getBean(TextEncryptorLocator.class); assertThat(textEncryptor).isInstanceOf(RsaSecretEncryptor.class); @@ -71,11 +73,13 @@ public class EncryptionAutoConfigurationTests { ConfigurableApplicationContext context = new SpringApplicationBuilder( DefaultTextEncryptionAutoConfiguration.class, RsaEncryptionAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class, - PropertyPlaceholderAutoConfiguration.class).properties("server.port=0", "encrypt.key=mykey").run(); + PropertyPlaceholderAutoConfiguration.class) + .properties("server.port=0", "encrypt.key=mykey") + .run(); TextEncryptor textEncryptor = context.getBean(TextEncryptor.class); String[] textEncryptorLocatorNames = context.getBeanNamesForType(TextEncryptorLocator.class); assertThat(textEncryptor.getClass().getName()) - .isEqualTo("org.springframework.security.crypto.encrypt.HexEncodingTextEncryptor"); + .isEqualTo("org.springframework.security.crypto.encrypt.HexEncodingTextEncryptor"); assertThat(textEncryptorLocatorNames).isEmpty(); context.close(); } @@ -86,7 +90,8 @@ public class EncryptionAutoConfigurationTests { DefaultTextEncryptionAutoConfiguration.class, RsaEncryptionAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class, PropertyPlaceholderAutoConfiguration.class) - .properties("server.port=0", "spring.cloud.bootstrap.enabled=true").run(); + .properties("server.port=0", "spring.cloud.bootstrap.enabled=true") + .run(); TextEncryptor textEncryptor = context.getBean(TextEncryptor.class); String[] textEncryptorLocatorNames = context.getBeanNamesForType(TextEncryptorLocator.class); assertThat(textEncryptor.getClass().isInstance(Encryptors.noOpText().getClass())); @@ -100,10 +105,11 @@ public class EncryptionAutoConfigurationTests { DefaultTextEncryptionAutoConfiguration.class, RsaEncryptionAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class, PropertyPlaceholderAutoConfiguration.class) - .properties("server.port=0", "spring.cloud.bootstrap.enabled=true", "encrypt.key=mykey").run(); + .properties("server.port=0", "spring.cloud.bootstrap.enabled=true", "encrypt.key=mykey") + .run(); TextEncryptor textEncryptor = context.getBean(TextEncryptor.class); assertThat(textEncryptor.getClass().getName()) - .isEqualTo("org.springframework.security.crypto.encrypt.HexEncodingTextEncryptor"); + .isEqualTo("org.springframework.security.crypto.encrypt.HexEncodingTextEncryptor"); context.close(); } @@ -113,10 +119,10 @@ public class EncryptionAutoConfigurationTests { DefaultTextEncryptionAutoConfiguration.class, RsaEncryptionAutoConfiguration.class, ServletWebServerFactoryAutoConfiguration.class, ServerProperties.class, PropertyPlaceholderAutoConfiguration.class) - .properties("server.port=0", "spring.cloud.bootstrap.enabled=true", - "encrypt.key-store.location=classpath:server.jks", "encrypt.key-store.password=letmein", - "encrypt.key-store.alias=myKey") - .run(); + .properties("server.port=0", "spring.cloud.bootstrap.enabled=true", + "encrypt.key-store.location=classpath:server.jks", "encrypt.key-store.password=letmein", + "encrypt.key-store.alias=myKey") + .run(); TextEncryptor textEncryptor = context.getBean(TextEncryptor.class); TextEncryptorLocator textEncryptorLocator = context.getBean(TextEncryptorLocator.class); assertThat(textEncryptor).isInstanceOf(LocatorTextEncryptor.class); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerMultiTextEncryptorTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerMultiTextEncryptorTests.java index faa45c39..f750af60 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerMultiTextEncryptorTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerMultiTextEncryptorTests.java @@ -50,7 +50,7 @@ public class EncryptionControllerMultiTextEncryptorTests { // then assertThat(this.controller.decrypt(this.application, this.profiles, encrypted, TEXT_PLAIN)) - .isEqualTo(this.data); + .isEqualTo(this.data); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerTests.java index 29adf47a..36a9f28e 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EncryptionControllerTests.java @@ -46,13 +46,13 @@ public class EncryptionControllerTests { @Test public void cannotDecryptWithoutKey() { assertThatExceptionOfType(EncryptionTooWeakException.class) - .isThrownBy(() -> this.controller.decrypt("foo", MediaType.TEXT_PLAIN)); + .isThrownBy(() -> this.controller.decrypt("foo", MediaType.TEXT_PLAIN)); } @Test public void cannotDecryptWithNoopEncryptor() { assertThatExceptionOfType(EncryptionTooWeakException.class) - .isThrownBy(() -> this.controller.decrypt("foo", MediaType.TEXT_PLAIN)); + .isThrownBy(() -> this.controller.decrypt("foo", MediaType.TEXT_PLAIN)); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelperTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelperTests.java index a2ef5359..64aeb6df 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelperTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/EnvironmentPrefixHelperTests.java @@ -85,7 +85,7 @@ public class EnvironmentPrefixHelperTests { @Test public void testTextWithCurlyBracesPrefix() { assertThat(this.helper.stripPrefix("{key:foo}{name:bar}textwith}brac{es{and}prefix")) - .isEqualTo("textwith}brac{es{and}prefix"); + .isEqualTo("textwith}brac{es{and}prefix"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/vault/VaultEnvironmentEncryptorTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/vault/VaultEnvironmentEncryptorTests.java index 8d77e854..617a75b2 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/vault/VaultEnvironmentEncryptorTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/encryption/vault/VaultEnvironmentEncryptorTests.java @@ -53,7 +53,7 @@ public class VaultEnvironmentEncryptorTests { // then assertThat(encryptor.decrypt(environment).getPropertySources().get(0).getSource().get(environment.getName())) - .isEqualTo(secret); + .isEqualTo(secret); } @Test @@ -73,7 +73,7 @@ public class VaultEnvironmentEncryptorTests { // then assertThat(encryptor.decrypt(environment).getPropertySources().get(0).getSource().get(environment.getName())) - .isNull(); + .isNull(); } @Test @@ -88,11 +88,11 @@ public class VaultEnvironmentEncryptorTests { // when Environment environment = new Environment("name", "profile", "label"); environment - .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); + .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); // then assertThat(encryptor.decrypt(environment).getPropertySources().get(0).getSource().get(environment.getName())) - .isEqualTo(value); + .isEqualTo(value); } @Test @@ -107,14 +107,14 @@ public class VaultEnvironmentEncryptorTests { // when Environment environment = new Environment("name", "profile", "label"); environment - .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); + .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); // then Environment processedEnvironment = encryptor.decrypt(environment); assertThat(processedEnvironment.getPropertySources().get(0).getSource().get(environment.getName())).isNull(); assertThat(processedEnvironment.getPropertySources().get(0).getSource().get("invalid." + environment.getName())) - .isEqualTo(""); + .isEqualTo(""); } @Test @@ -129,14 +129,14 @@ public class VaultEnvironmentEncryptorTests { // when Environment environment = new Environment("name", "profile", "label"); environment - .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); + .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); // then Environment processedEnvironment = encryptor.decrypt(environment); assertThat(processedEnvironment.getPropertySources().get(0).getSource().get(environment.getName())).isNull(); assertThat(processedEnvironment.getPropertySources().get(0).getSource().get("invalid." + environment.getName())) - .isEqualTo(""); + .isEqualTo(""); } @Test @@ -151,14 +151,14 @@ public class VaultEnvironmentEncryptorTests { // when Environment environment = new Environment("name", "profile", "label"); environment - .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); + .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); // then Environment processedEnvironment = encryptor.decrypt(environment); assertThat(processedEnvironment.getPropertySources().get(0).getSource().get(environment.getName())).isNull(); assertThat(processedEnvironment.getPropertySources().get(0).getSource().get("invalid." + environment.getName())) - .isEqualTo(""); + .isEqualTo(""); } @Test @@ -173,14 +173,14 @@ public class VaultEnvironmentEncryptorTests { // when Environment environment = new Environment("name", "profile", "label"); environment - .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); + .add(new PropertySource("a", Collections.singletonMap(environment.getName(), value))); // then Environment processedEnvironment = encryptor.decrypt(environment); assertThat(processedEnvironment.getPropertySources().get(0).getSource().get(environment.getName())).isNull(); assertThat(processedEnvironment.getPropertySources().get(0).getSource().get("invalid." + environment.getName())) - .isEqualTo(""); + .isEqualTo(""); } private VaultResponse withVaultResponse(String key, Object value) { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AWSParameterStoreEnvironmentRepositoryUnitTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AWSParameterStoreEnvironmentRepositoryUnitTest.java index a10df257..4fba1af8 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AWSParameterStoreEnvironmentRepositoryUnitTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AWSParameterStoreEnvironmentRepositoryUnitTest.java @@ -112,10 +112,12 @@ public class AWSParameterStoreEnvironmentRepositoryUnitTest { for (PropertySource ps : environment.getPropertySources()) { String path = StringUtils.delete(ps.getName(), environmentProperties.getOrigin()); - 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(); Set parameters = getParameters(ps, path, withSlashesForPropertyName); @@ -132,8 +134,10 @@ public class AWSParameterStoreEnvironmentRepositoryUnitTest { if (i == 0) { nextToken = generateNextToken(); - GetParametersByPathResponse responseClone = response.toBuilder().parameters(chunk) - .nextToken(nextToken).build(); + GetParametersByPathResponse responseClone = response.toBuilder() + .parameters(chunk) + .nextToken(nextToken) + .build(); when(ssmClient.getParametersByPath(eq(request))).thenReturn(responseClone); } @@ -148,8 +152,10 @@ public class AWSParameterStoreEnvironmentRepositoryUnitTest { GetParametersByPathRequest requestClone = request.toBuilder().nextToken(nextToken).build(); - GetParametersByPathResponse responseClone = response.toBuilder().parameters(chunk) - .nextToken(newNextToken).build(); + GetParametersByPathResponse responseClone = response.toBuilder() + .parameters(chunk) + .nextToken(newNextToken) + .build(); when(ssmClient.getParametersByPath(eq(requestClone))).thenReturn(responseClone); @@ -165,10 +171,13 @@ public class AWSParameterStoreEnvironmentRepositoryUnitTest { private Set getParameters(PropertySource propertySource, String path, boolean withSlashesForPropertyName) { - Function, Parameter> mapper = p -> Parameter - .builder().name(path + (withSlashesForPropertyName - ? ((String) p.getKey()).replace(".", DEFAULT_PATH_SEPARATOR) : p.getKey())) - .type(ParameterType.STRING).value((String) p.getValue()).version(1L).build(); + Function, Parameter> mapper = p -> Parameter.builder() + .name(path + (withSlashesForPropertyName ? ((String) p.getKey()).replace(".", DEFAULT_PATH_SEPARATOR) + : p.getKey())) + .type(ParameterType.STRING) + .value((String) p.getValue()) + .version(1L) + .build(); return propertySource.getSource().entrySet().stream().map(mapper).collect(Collectors.toSet()); } @@ -177,7 +186,7 @@ public class AWSParameterStoreEnvironmentRepositoryUnitTest { AtomicInteger counter = new AtomicInteger(); Collector>> collector = Collectors - .groupingBy(p -> counter.getAndIncrement() / environmentProperties.getMaxResults(), Collectors.toSet()); + .groupingBy(p -> counter.getAndIncrement() / environmentProperties.getMaxResults(), Collectors.toSet()); return new ArrayList<>(parameters.stream().collect(collector).values()); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsParameterStoreEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsParameterStoreEnvironmentRepositoryTests.java index 2648f838..aca71887 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsParameterStoreEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsParameterStoreEnvironmentRepositoryTests.java @@ -63,14 +63,17 @@ public class AwsParameterStoreEnvironmentRepositoryTests { @Container private static final LocalStackContainer localstack = new LocalStackContainer( - DockerImageName.parse("localstack/localstack:1.3.1")).withServices(SSM); + DockerImageName.parse("localstack/localstack:1.3.1")) + .withServices(SSM); private final StaticCredentialsProvider staticCredentialsProvider = StaticCredentialsProvider - .create(AwsBasicCredentials.create(localstack.getAccessKey(), localstack.getSecretKey())); + .create(AwsBasicCredentials.create(localstack.getAccessKey(), localstack.getSecretKey())); - private final SsmClient ssmClient = SsmClient.builder().region(Region.of(localstack.getRegion())) - .credentialsProvider(staticCredentialsProvider).endpointOverride(localstack.getEndpointOverride(SSM)) - .build(); + private final SsmClient ssmClient = SsmClient.builder() + .region(Region.of(localstack.getRegion())) + .credentialsProvider(staticCredentialsProvider) + .endpointOverride(localstack.getEndpointOverride(SSM)) + .build(); private final ConfigServerProperties configServerProperties = new ConfigServerProperties(); @@ -505,8 +508,8 @@ public class AwsParameterStoreEnvironmentRepositoryTests { Environment expected = new Environment(application, profiles, null, null, null); - expected.addAll( - Arrays.asList(appSpecificProdParamsPs, sharedProdParamsPs, appSpecificParamsPs, sharedParamsPs)); + expected + .addAll(Arrays.asList(appSpecificProdParamsPs, sharedProdParamsPs, appSpecificParamsPs, sharedParamsPs)); putParameters(expected); @@ -706,10 +709,13 @@ public class AwsParameterStoreEnvironmentRepositoryTests { private Set getParameters(PropertySource propertySource, String path, boolean withSlashesForPropertyName) { - Function, Parameter> mapper = p -> Parameter - .builder().name(path + (withSlashesForPropertyName - ? ((String) p.getKey()).replace(".", DEFAULT_PATH_SEPARATOR) : p.getKey())) - .type(ParameterType.STRING).value((String) p.getValue()).version(1L).build(); + Function, Parameter> mapper = p -> Parameter.builder() + .name(path + (withSlashesForPropertyName ? ((String) p.getKey()).replace(".", DEFAULT_PATH_SEPARATOR) + : p.getKey())) + .type(ParameterType.STRING) + .value((String) p.getValue()) + .version(1L) + .build(); return propertySource.getSource().entrySet().stream().map(mapper).collect(Collectors.toSet()); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsS3EnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsS3EnvironmentRepositoryTests.java index d34e53c5..56d802d0 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsS3EnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsS3EnvironmentRepositoryTests.java @@ -58,16 +58,19 @@ public class AwsS3EnvironmentRepositoryTests { @Container private static final LocalStackContainer localstack = new LocalStackContainer( - DockerImageName.parse("localstack/localstack:1.3.1")).withServices(S3); + DockerImageName.parse("localstack/localstack:1.3.1")) + .withServices(S3); private final ConfigServerProperties server = new ConfigServerProperties(); private final StaticCredentialsProvider staticCredentialsProvider = StaticCredentialsProvider - .create(AwsBasicCredentials.create(localstack.getAccessKey(), localstack.getSecretKey())); + .create(AwsBasicCredentials.create(localstack.getAccessKey(), localstack.getSecretKey())); - private final S3Client s3Client = S3Client.builder().region(Region.of(localstack.getRegion())) - .credentialsProvider(staticCredentialsProvider).endpointOverride(localstack.getEndpointOverride(S3)) - .build(); + private final S3Client s3Client = S3Client.builder() + .region(Region.of(localstack.getRegion())) + .credentialsProvider(staticCredentialsProvider) + .endpointOverride(localstack.getEndpointOverride(S3)) + .build(); private final EnvironmentRepository envRepo = new AwsS3EnvironmentRepository(s3Client, "bucket1", server); @@ -104,16 +107,17 @@ public class AwsS3EnvironmentRepositoryTests { @BeforeAll public static void createBucket() { StaticCredentialsProvider staticCredentialsProvider = StaticCredentialsProvider - .create(AwsBasicCredentials.create(localstack.getAccessKey(), localstack.getSecretKey())); - S3Client s3Client = S3Client.builder().region(Region.of(localstack.getRegion())) - .credentialsProvider(staticCredentialsProvider).endpointOverride(localstack.getEndpointOverride(S3)) - .build(); + .create(AwsBasicCredentials.create(localstack.getAccessKey(), localstack.getSecretKey())); + S3Client s3Client = S3Client.builder() + .region(Region.of(localstack.getRegion())) + .credentialsProvider(staticCredentialsProvider) + .endpointOverride(localstack.getEndpointOverride(S3)) + .build(); s3Client.createBucket(CreateBucketRequest.builder().bucket("bucket1").build()); - s3Client.putBucketVersioning( - PutBucketVersioningRequest.builder().bucket("bucket1") - .versioningConfiguration( - VersioningConfiguration.builder().status(BucketVersioningStatus.ENABLED).build()) - .build()); + s3Client.putBucketVersioning(PutBucketVersioningRequest.builder() + .bucket("bucket1") + .versioningConfiguration(VersioningConfiguration.builder().status(BucketVersioningStatus.ENABLED).build()) + .build()); } @AfterEach @@ -283,11 +287,11 @@ public class AwsS3EnvironmentRepositoryTests { assertThat(repository.getLocations("app", "default", "main")).isEqualTo( new SearchPathLocator.Locations("app", "default", "main", null, new String[] { "s3://test/main" })); - assertThat(repository.getLocations("app", "default", null)).isEqualTo( - new SearchPathLocator.Locations("app", "default", null, null, new String[] { "s3://test/" })); + assertThat(repository.getLocations("app", "default", null)) + .isEqualTo(new SearchPathLocator.Locations("app", "default", null, null, new String[] { "s3://test/" })); assertThat(repository.getLocations("app", "default", "")) - .isEqualTo(new SearchPathLocator.Locations("app", "default", "", null, new String[] { "s3://test/" })); + .isEqualTo(new SearchPathLocator.Locations("app", "default", "", null, new String[] { "s3://test/" })); ConfigServerProperties configServerProperties = new ConfigServerProperties(); configServerProperties.setDefaultLabel("defaultlabel"); @@ -303,8 +307,10 @@ public class AwsS3EnvironmentRepositoryTests { private String putFiles(String fileName, String propertyContent) { toBeRemoved.add(fileName); - return s3Client.putObject(PutObjectRequest.builder().bucket("bucket1").key(fileName).build(), - RequestBody.fromString((propertyContent))).versionId(); + return s3Client + .putObject(PutObjectRequest.builder().bucket("bucket1").key(fileName).build(), + RequestBody.fromString((propertyContent))) + .versionId(); } private void assertExpectedEnvironment(Environment env, String applicationName, String label, String versionId, diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsSecretsManagerEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsSecretsManagerEnvironmentRepositoryTests.java index 6164efa5..eb187484 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsSecretsManagerEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/AwsSecretsManagerEnvironmentRepositoryTests.java @@ -65,16 +65,19 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { @Container private static final LocalStackContainer localstack = new LocalStackContainer( - DockerImageName.parse("localstack/localstack:1.3.1")).withServices(SECRETSMANAGER); + DockerImageName.parse("localstack/localstack:1.3.1")) + .withServices(SECRETSMANAGER); private static final Log log = LogFactory.getLog(AwsSecretsManagerEnvironmentRepository.class); private final StaticCredentialsProvider staticCredentialsProvider = StaticCredentialsProvider - .create(AwsBasicCredentials.create(localstack.getAccessKey(), localstack.getSecretKey())); + .create(AwsBasicCredentials.create(localstack.getAccessKey(), localstack.getSecretKey())); private final SecretsManagerClient smClient = SecretsManagerClient.builder() - .region(Region.of(localstack.getRegion())).credentialsProvider(staticCredentialsProvider) - .endpointOverride(localstack.getEndpointOverride(SECRETSMANAGER)).build(); + .region(Region.of(localstack.getRegion())) + .credentialsProvider(staticCredentialsProvider) + .endpointOverride(localstack.getEndpointOverride(SECRETSMANAGER)) + .build(); private final ConfigServerProperties configServerProperties = new ConfigServerProperties(); @@ -250,11 +253,11 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { @AfterEach public void cleanUp() { markedForDeletion - .forEach(value -> smClient.restoreSecret(RestoreSecretRequest.builder().secretId(value).build())); + .forEach(value -> smClient.restoreSecret(RestoreSecretRequest.builder().secretId(value).build())); markedForDeletion.clear(); toBeRemoved.forEach(value -> smClient - .deleteSecret(DeleteSecretRequest.builder().secretId(value).forceDeleteWithoutRecovery(true).build())); + .deleteSecret(DeleteSecretRequest.builder().secretId(value).forceDeleteWithoutRecovery(true).build())); toBeRemoved.clear(); } @@ -332,7 +335,7 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { Environment expectedEnv = new Environment(defaultApplication, profiles, defaultLabel, null, null); expectedEnv - .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); + .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); putSecrets(expectedEnv); @@ -438,7 +441,7 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { Environment expectedEnv = new Environment(application, profiles, defaultLabel, null, null); expectedEnv - .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); + .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); putSecrets(expectedEnv); @@ -544,7 +547,7 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { Environment expectedEnv = new Environment(application, profiles, defaultLabel, null, null); expectedEnv - .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); + .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); putSecrets(expectedEnv); @@ -763,8 +766,8 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { getApplicationProperties()); Environment expectedEnv = new Environment(application, profiles, defaultLabel, null, null); - expectedEnv.addAll( - Arrays.asList(fooProdProperties, applicationProdProperties, fooProperties, applicationProperties)); + expectedEnv + .addAll(Arrays.asList(fooProdProperties, applicationProdProperties, fooProperties, applicationProperties)); putSecrets(expectedEnv); @@ -1304,7 +1307,7 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { Environment expectedEnv = new Environment(defaultApplication, profiles, label, null, null); expectedEnv - .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); + .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); putSecrets(expectedEnv); @@ -1410,7 +1413,7 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { Environment expectedEnv = new Environment(application, profiles, label, null, null); expectedEnv - .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); + .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); putSecrets(expectedEnv); @@ -1516,7 +1519,7 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { Environment expectedEnv = new Environment(application, profiles, label, null, null); expectedEnv - .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); + .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); putSecrets(expectedEnv); @@ -1739,8 +1742,8 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { getApplicationReleaseProperties()); Environment expectedEnv = new Environment(application, profiles, label, null, null); - expectedEnv.addAll( - Arrays.asList(fooProdProperties, applicationProdProperties, fooProperties, applicationProperties)); + expectedEnv + .addAll(Arrays.asList(fooProdProperties, applicationProdProperties, fooProperties, applicationProperties)); putSecrets(expectedEnv); @@ -2000,7 +2003,7 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { Environment environment = new Environment(defaultApplication, profiles, null, null, null); environment - .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); + .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); putSecrets(environment); @@ -2102,7 +2105,7 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { Environment environment = new Environment(application, profiles, null, null, null); environment - .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); + .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); putSecrets(environment); @@ -2204,7 +2207,7 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { Environment environment = new Environment(application, profiles, null, null, null); environment - .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); + .addAll(Arrays.asList(applicationProdProperties, applicationDefaultProperties, applicationProperties)); putSecrets(environment); @@ -2416,8 +2419,8 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { getApplicationProperties()); Environment environment = new Environment(application, profiles, null, null, null); - environment.addAll( - Arrays.asList(fooProdProperties, applicationProdProperties, fooProperties, applicationProperties)); + environment + .addAll(Arrays.asList(fooProdProperties, applicationProdProperties, fooProperties, applicationProperties)); putSecrets(environment); @@ -2641,10 +2644,13 @@ public class AwsSecretsManagerEnvironmentRepositoryTests { String path = StringUtils.delete(ps.getName(), environmentProperties.getOrigin()); String secrets = getSecrets(ps); CreateSecretResponse response = smClient - .createSecret(CreateSecretRequest.builder().name(path).secretString(secrets).build()); + .createSecret(CreateSecretRequest.builder().name(path).secretString(secrets).build()); if (!ObjectUtils.isEmpty(label)) { - smClient.updateSecretVersionStage(UpdateSecretVersionStageRequest.builder().secretId(path) - .moveToVersionId(response.versionId()).versionStage(label).build()); + smClient.updateSecretVersionStage(UpdateSecretVersionStageRequest.builder() + .secretId(path) + .moveToVersionId(response.versionId()) + .versionStage(label) + .build()); } toBeRemoved.add(path); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java index 7fe1d0e4..f9f9dc3f 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CompositeEnvironmentRepositoryTests.java @@ -204,7 +204,7 @@ public class CompositeEnvironmentRepositoryTests { SearchPathCompositeEnvironmentRepository compositeRepo = new SearchPathCompositeEnvironmentRepository(repos, ObservationRegistry.NOOP, true); assertThatExceptionOfType(RepositoryException.class) - .isThrownBy(() -> compositeRepo.getLocations("app", "dev", "label")); + .isThrownBy(() -> compositeRepo.getLocations("app", "dev", "label")); } private static class TestOrderedEnvironmentRepository implements EnvironmentRepository, SearchPathLocator, Ordered { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactoryIntegrationTests.java index 7c35efa9..48167968 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ConfigurableHttpConnectionFactoryIntegrationTests.java @@ -93,7 +93,8 @@ public class ConfigurableHttpConnectionFactoryIntegrationTests { Assertions.assertThatThrownBy(() -> { String repoUrl = "https://myrepo/repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, null, AUTHENTICATED_HTTPS_PROXY)).run(); + .properties(gitProperties(repoUrl, null, AUTHENTICATED_HTTPS_PROXY)) + .run(); HttpClient httpClient = getHttpClientForUrl(repoUrl); makeRequest(httpClient, "https://somehost"); }).hasCauseInstanceOf(UnknownHostException.class).hasMessageContaining(AUTHENTICATED_HTTPS_PROXY.getHost()); @@ -105,7 +106,8 @@ public class ConfigurableHttpConnectionFactoryIntegrationTests { Assertions.assertThatThrownBy(() -> { String repoUrl = "https://myrepo/repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, null, HTTPS_PROXY)).run(); + .properties(gitProperties(repoUrl, null, HTTPS_PROXY)) + .run(); HttpClient httpClient = getHttpClientForUrl(repoUrl); makeRequest(httpClient, "https://somehost"); }).hasCauseInstanceOf(UnknownHostException.class).hasMessageContaining(HTTPS_PROXY.getHost()); @@ -116,7 +118,8 @@ public class ConfigurableHttpConnectionFactoryIntegrationTests { Assertions.assertThatThrownBy(() -> { String repoUrl = "https://myrepo/{placeholder1}/{placeholder2}-repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, null, HTTPS_PROXY)).run(); + .properties(gitProperties(repoUrl, null, HTTPS_PROXY)) + .run(); HttpClient httpClient = getHttpClientForUrl( "https://myrepo/someplaceholdervalue/anotherplaceholdervalue-repo.git"); makeRequest(httpClient, "https://somehost"); @@ -128,7 +131,8 @@ public class ConfigurableHttpConnectionFactoryIntegrationTests { Assertions.assertThatThrownBy(() -> { String repoUrl = "https://myrepo/repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, null, HTTPS_PROXY)).run(); + .properties(gitProperties(repoUrl, null, HTTPS_PROXY)) + .run(); HttpClient httpClient = getHttpClientForUrl(repoUrl); makeRequest(httpClient, "http://somehost"); }).hasCauseInstanceOf(UnknownHostException.class).hasMessageContaining(HTTPS_PROXY.getHost()); @@ -139,7 +143,8 @@ public class ConfigurableHttpConnectionFactoryIntegrationTests { Assertions.assertThatThrownBy(() -> { String repoUrl = "https://myrepo/repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, AUTHENTICATED_HTTP_PROXY, null)).run(); + .properties(gitProperties(repoUrl, AUTHENTICATED_HTTP_PROXY, null)) + .run(); HttpClient httpClient = getHttpClientForUrl(repoUrl); makeRequest(httpClient, "http://somehost"); }).hasCauseInstanceOf(UnknownHostException.class).hasMessageContaining(AUTHENTICATED_HTTP_PROXY.getHost()); @@ -150,7 +155,8 @@ public class ConfigurableHttpConnectionFactoryIntegrationTests { Assertions.assertThatThrownBy(() -> { String repoUrl = "https://myrepo/repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, HTTP_PROXY, null)).run(); + .properties(gitProperties(repoUrl, HTTP_PROXY, null)) + .run(); HttpClient httpClient = getHttpClientForUrl(repoUrl); makeRequest(httpClient, "http://somehost"); }).hasCauseInstanceOf(UnknownHostException.class).hasMessageContaining(HTTP_PROXY.getHost()); @@ -161,7 +167,8 @@ public class ConfigurableHttpConnectionFactoryIntegrationTests { Assertions.assertThatThrownBy(() -> { String repoUrl = "https://myrepo/{placeholder}-repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, HTTP_PROXY, null)).run(); + .properties(gitProperties(repoUrl, HTTP_PROXY, null)) + .run(); HttpClient httpClient = getHttpClientForUrl("https://myrepo/someplaceholdervalue-repo.git"); makeRequest(httpClient, "http://somehost"); }).hasCauseInstanceOf(UnknownHostException.class).hasMessageContaining(HTTP_PROXY.getHost()); @@ -172,7 +179,8 @@ public class ConfigurableHttpConnectionFactoryIntegrationTests { Assertions.assertThatThrownBy(() -> { String repoUrl = "https://myrepo/repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties(gitProperties(repoUrl, HTTP_PROXY, null)).run(); + .properties(gitProperties(repoUrl, HTTP_PROXY, null)) + .run(); HttpClient httpClient = getHttpClientForUrl(repoUrl); makeRequest(httpClient, "https://somehost"); }).hasCauseInstanceOf(UnknownHostException.class).hasMessageContaining(HTTP_PROXY.getHost()); @@ -198,7 +206,8 @@ public class ConfigurableHttpConnectionFactoryIntegrationTests { }); String repoUrl = "https://myrepo/repo.git"; new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties(new String[] { "spring.cloud.config.server.git.uri=" + repoUrl }).run(); + .properties(new String[] { "spring.cloud.config.server.git.uri=" + repoUrl }) + .run(); HttpClient httpClient = getHttpClientForUrl(repoUrl); makeRequest(httpClient, "http://somehost"); }).hasCauseInstanceOf(UnknownHostException.class).hasMessageContaining(HTTP_PROXY.getHost()); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryTests.java index 402327bc..e3347bfd 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/CredhubEnvironmentRepositoryTests.java @@ -68,7 +68,7 @@ public class CredhubEnvironmentRepositoryTests { assertThat(environment.getPropertySources()).hasSize(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo("credhub-my-application-production-mylabel"); + .isEqualTo("credhub-my-application-production-mylabel"); assertThat(environment.getPropertySources().get(0).getSource()).isEmpty(); } @@ -84,7 +84,7 @@ public class CredhubEnvironmentRepositoryTests { assertThat(environment.getPropertySources()).hasSize(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo("credhub-my-application-default-master"); + .isEqualTo("credhub-my-application-default-master"); assertThat(environment.getPropertySources().get(0).getSource()).isEqualTo(singletonMap("key1", "value1")); } @@ -100,7 +100,7 @@ public class CredhubEnvironmentRepositoryTests { assertThat(environment.getPropertySources()).hasSize(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo("credhub-my-application-production-mylabel"); + .isEqualTo("credhub-my-application-production-mylabel"); assertThat(environment.getPropertySources().get(0).getSource()).isEqualTo(singletonMap("key1", "value1")); } @@ -118,11 +118,11 @@ public class CredhubEnvironmentRepositoryTests { assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo("credhub-my-application-production-mylabel"); + .isEqualTo("credhub-my-application-production-mylabel"); assertThat(environment.getPropertySources().get(0).getSource()).isEqualTo(singletonMap("key1", "value1")); assertThat(environment.getPropertySources().get(1).getName()) - .isEqualTo("credhub-my-application-cloud-mylabel"); + .isEqualTo("credhub-my-application-cloud-mylabel"); assertThat(environment.getPropertySources().get(1).getSource()).isEqualTo(singletonMap("key2", "value2")); } @@ -132,17 +132,17 @@ public class CredhubEnvironmentRepositoryTests { SimpleCredentialName togglesCredentialName = new SimpleCredentialName(expectedPath + "/toggles"); SimpleCredentialName absCredentialName = new SimpleCredentialName(expectedPath + "/abs"); - when(this.credhubCredentialOperations.findByPath(expectedPath)).thenReturn( - asList(new CredentialSummary(togglesCredentialName), new CredentialSummary(absCredentialName))); + when(this.credhubCredentialOperations.findByPath(expectedPath)) + .thenReturn(asList(new CredentialSummary(togglesCredentialName), new CredentialSummary(absCredentialName))); JsonCredential credentials = new JsonCredential(); credentials.put("key1", "value1"); when(this.credhubCredentialOperations.getByName(togglesCredentialName, JsonCredential.class)) - .thenReturn(new CredentialDetails<>("id1", togglesCredentialName, CredentialType.JSON, credentials)); + .thenReturn(new CredentialDetails<>("id1", togglesCredentialName, CredentialType.JSON, credentials)); JsonCredential otherCredentials = new JsonCredential(); otherCredentials.put("key2", "value2"); when(this.credhubCredentialOperations.getByName(absCredentialName, JsonCredential.class)) - .thenReturn(new CredentialDetails<>("id2", absCredentialName, CredentialType.JSON, otherCredentials)); + .thenReturn(new CredentialDetails<>("id2", absCredentialName, CredentialType.JSON, otherCredentials)); Environment environment = this.credhubEnvironmentRepository.findOne("my-application", "production", "mylabel"); @@ -152,7 +152,7 @@ public class CredhubEnvironmentRepositoryTests { assertThat(environment.getPropertySources()).hasSize(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo("credhub-my-application-production-mylabel"); + .isEqualTo("credhub-my-application-production-mylabel"); HashMap expectedValues = new HashMap<>(); expectedValues.put("key1", "value1"); expectedValues.put("key2", "value2"); @@ -172,10 +172,10 @@ public class CredhubEnvironmentRepositoryTests { assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo("credhub-my-application-production-mylabel"); + .isEqualTo("credhub-my-application-production-mylabel"); assertThat(environment.getPropertySources().get(0).getSource()).isEqualTo(singletonMap("key1", "value1")); assertThat(environment.getPropertySources().get(1).getName()) - .isEqualTo("credhub-application-production-mylabel"); + .isEqualTo("credhub-application-production-mylabel"); assertThat(environment.getPropertySources().get(1).getSource()).isEqualTo(singletonMap("key2", "value2")); } @@ -194,13 +194,13 @@ public class CredhubEnvironmentRepositoryTests { assertThat(environment.getPropertySources()).hasSize(4); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo("credhub-my-application-production-mylabel"); + .isEqualTo("credhub-my-application-production-mylabel"); assertThat(environment.getPropertySources().get(0).getSource()).isEqualTo(singletonMap("key1", "value1")); assertThat(environment.getPropertySources().get(1).getName()) - .isEqualTo("credhub-application-production-mylabel"); + .isEqualTo("credhub-application-production-mylabel"); assertThat(environment.getPropertySources().get(1).getSource()).isEqualTo(singletonMap("key2", "value2")); assertThat(environment.getPropertySources().get(2).getName()) - .isEqualTo("credhub-my-application-default-mylabel"); + .isEqualTo("credhub-my-application-default-mylabel"); assertThat(environment.getPropertySources().get(2).getSource()).isEqualTo(singletonMap("key3", "value3")); assertThat(environment.getPropertySources().get(3).getName()).isEqualTo("credhub-application-default-mylabel"); assertThat(environment.getPropertySources().get(3).getSource()).isEqualTo(singletonMap("key4", "value4")); @@ -209,12 +209,12 @@ public class CredhubEnvironmentRepositoryTests { private void stubCredentials(String expectedPath, String name, String key, String value) { SimpleCredentialName credentialsName = new SimpleCredentialName(expectedPath + "/" + name); when(this.credhubCredentialOperations.findByPath(expectedPath)) - .thenReturn(singletonList(new CredentialSummary(credentialsName))); + .thenReturn(singletonList(new CredentialSummary(credentialsName))); JsonCredential credentials = new JsonCredential(); credentials.put(key, value); when(this.credhubCredentialOperations.getByName(new SimpleCredentialName(expectedPath + "/" + name), JsonCredential.class)) - .thenReturn(new CredentialDetails<>("id1", credentialsName, CredentialType.JSON, credentials)); + .thenReturn(new CredentialDetails<>("id1", credentialsName, CredentialType.JSON, credentials)); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerIntegrationTests.java index 73c5d065..c58ae193 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerIntegrationTests.java @@ -76,7 +76,7 @@ class EnvironmentControllerIntegrationTests { public void environmentNoLabel() throws Exception { when(this.repository.findOne("foo", "default", null, false)).thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", "default", null, false); } @@ -86,7 +86,7 @@ class EnvironmentControllerIntegrationTests { dashEnvironment.add(new PropertySource("foo", new HashMap<>())); when(this.repository.findOne("foo", "dev-db", null, false)).thenReturn(dashEnvironment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/dev-db")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", "dev-db", null, false); } @@ -98,7 +98,7 @@ class EnvironmentControllerIntegrationTests { dashEnvironment.add(new PropertySource("foo", new HashMap<>())); when(this.repository.findOne("foo", profiles, null, false)).thenReturn(dashEnvironment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/" + profiles)) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", profiles, null, false); } @@ -109,7 +109,7 @@ class EnvironmentControllerIntegrationTests { Environment dashEnvironment = new Environment("foo", profiles); dashEnvironment.add(new PropertySource("foo", new HashMap<>())); this.mvc.perform(MockMvcRequestBuilders.get("/foo/" + profiles)) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); verifyNoInteractions(this.repository); } @@ -117,7 +117,7 @@ class EnvironmentControllerIntegrationTests { public void propertiesNoLabel() throws Exception { when(this.repository.findOne("foo", "default", null, false)).thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo-default.properties")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", "default", null, false); } @@ -125,7 +125,7 @@ class EnvironmentControllerIntegrationTests { public void propertiesLabel() throws Exception { when(this.repository.findOne("foo", "default", "label", false)).thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/label/foo-default.properties")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", "default", "label", false); } @@ -135,7 +135,7 @@ class EnvironmentControllerIntegrationTests { environment.add(new PropertySource("foo", new HashMap<>())); when(this.repository.findOne("foo-bar", "default", "label", false)).thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/label/foo-bar-default.properties")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo-bar", "default", "label", false); } @@ -144,7 +144,7 @@ class EnvironmentControllerIntegrationTests { when(this.repository.findOne("foo", "default", "label/spam", false)).thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/label(_)spam/foo-default.properties")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", "default", "label/spam", false); } @@ -152,38 +152,38 @@ class EnvironmentControllerIntegrationTests { public void environmentWithLabel() throws Exception { when(this.repository.findOne("foo", "default", "awesome", false)).thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/awesome")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void environmentWithMissingLabel() throws Exception { when(this.repository.findOne("foo", "default", "missing", false)) - .thenThrow(new NoSuchLabelException("Planned")); + .thenThrow(new NoSuchLabelException("Planned")); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/missing")) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test public void environmentWithMissingRepo() throws Exception { when(this.repository.findOne("foo", "default", "missing", false)) - .thenThrow(new NoSuchRepositoryException("Planned")); + .thenThrow(new NoSuchRepositoryException("Planned")); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/missing")) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test public void environmentWithLabelContainingPeriod() throws Exception { when(this.repository.findOne("foo", "default", "1.0.0", false)).thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/1.0.0")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void environmentWithLabelContainingSlash() throws Exception { when(this.repository.findOne("foo", "default", "feature/puff", false)).thenReturn(this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/feature(_)puff")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("\"propertySources\":"))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("\"propertySources\":"))); } @Test @@ -192,8 +192,8 @@ class EnvironmentControllerIntegrationTests { environment.add(new PropertySource("foo", new HashMap<>())); when(this.repository.findOne("foo/app", "default", null, false)).thenReturn(environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo(_)app/default")) - .andExpect(MockMvcResultMatchers.status().isOk()) - .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("\"propertySources\":"))); + .andExpect(MockMvcResultMatchers.status().isOk()) + .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("\"propertySources\":"))); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerTests.java index 415a33bd..7d0335dd 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentControllerTests.java @@ -239,7 +239,7 @@ class EnvironmentControllerTests { public void testEnvironmentNotFound() { this.controller.setAcceptEmpty(false); assertThatThrownBy(() -> this.controller.labelled("foo", "bar", null)) - .isInstanceOf(EnvironmentNotFoundException.class); + .isInstanceOf(EnvironmentNotFoundException.class); } @Test @@ -337,7 +337,9 @@ class EnvironmentControllerTests { when(this.repository.findOne("foo", "bar", null, false)).thenReturn(this.environment); String yaml = this.controller.yaml("foo", "bar", false).getBody(); assertThat("a:\n b:\n - d: e\n c: d\n - c: d\n".equals(yaml) - || "a:\n b:\n - c: d\n d: e\n - c: d\n".equals(yaml)).as("Wrong output: " + yaml).isTrue(); + || "a:\n b:\n - c: d\n d: e\n - c: d\n".equals(yaml)) + .as("Wrong output: " + yaml) + .isTrue(); } @Test @@ -394,7 +396,7 @@ class EnvironmentControllerTests { when(this.repository.findOne("foo", "bar", null, false)).thenReturn(this.environment); String json = this.controller.jsonProperties("foo", "bar", false).getBody(); assertThat(json).as("Wrong output: " + json) - .isEqualTo("{\"a\":{\"b\":[{\"c\":\"x\",\"d\":[\"xx\",\"yy\"]},{\"c\":\"y\",\"e\":[{\"d\":\"z\"}]}]}}"); + .isEqualTo("{\"a\":{\"b\":[{\"c\":\"x\",\"d\":[\"xx\",\"yy\"]},{\"c\":\"y\",\"e\":[{\"d\":\"z\"}]}]}}"); } @Test @@ -525,31 +527,31 @@ class EnvironmentControllerTests { @Test public void labelWithPreviousDirectory() { assertThatThrownBy(() -> this.controller.labelled("foo", "bar", "..(_)..")) - .isInstanceOf(InvalidEnvironmentRequestException.class); + .isInstanceOf(InvalidEnvironmentRequestException.class); } @Test public void labelWithPreviousDirectoryEncodedParenthesis() { assertThatThrownBy(() -> this.controller.labelled("foo", "bar", "..%28_%29..")) - .isInstanceOf(InvalidEnvironmentRequestException.class); + .isInstanceOf(InvalidEnvironmentRequestException.class); } @Test public void labelWithPreviousDirectoryAllEncoded() { assertThatThrownBy(() -> this.controller.labelled("foo", "bar", "%2E%2E%28%5F%29%2E%2E")) - .isInstanceOf(InvalidEnvironmentRequestException.class); + .isInstanceOf(InvalidEnvironmentRequestException.class); } @Test public void nameWithPound() { assertThatThrownBy(() -> this.controller.labelled("foo#", "bar", "mylabel")) - .isInstanceOf(InvalidEnvironmentRequestException.class); + .isInstanceOf(InvalidEnvironmentRequestException.class); } @Test public void nameWithPoundEncoded() { assertThatThrownBy(() -> this.controller.labelled("foo%23", "bar", "mylabel")) - .isInstanceOf(InvalidEnvironmentRequestException.class); + .isInstanceOf(InvalidEnvironmentRequestException.class); } abstract class MockMvcTestCases { @@ -559,98 +561,98 @@ class EnvironmentControllerTests { @Test public void mappingForEnvironment() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo", "bar", null, false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/bar")).andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void mappingForLabelledEnvironment() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo", "bar", "other", false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo/bar/other")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void environmentMissing() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo1", "notfound", null, false)) - .thenThrow(new EnvironmentNotFoundException("Missing Environment")); + .thenThrow(new EnvironmentNotFoundException("Missing Environment")); this.mvc.perform(MockMvcRequestBuilders.get("/foo1/notfound")) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @Test public void mappingForYaml() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo", "bar", null, false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo-bar.yml")) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)) - .andExpect(MockMvcResultMatchers.content().string("{}\n")); + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)) + .andExpect(MockMvcResultMatchers.content().string("{}\n")); } @Test public void mappingForJson() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo", "bar", null, false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo-bar.json")) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(MockMvcResultMatchers.content().string("{}")); + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) + .andExpect(MockMvcResultMatchers.content().string("{}")); } @Test public void mappingForLabelledYaml() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo", "bar", "other", false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/other/foo-bar.yml")) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)); + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)); } @Test public void mappingForLabelledProperties() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo", "bar", "other", false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/other/foo-bar.properties")) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)); + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)); } @Test public void mappingForProperties() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo", "bar", null, false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo-bar.properties")) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)); + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)); } @Test public void mappingForLabelledYamlWithHyphen() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo-bar-foo2-bar2", "spam", "other", false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/other/foo-bar-foo2-bar2-spam.yml")) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)); + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.TEXT_PLAIN)); } @Test public void mappingforLabelledJsonProperties() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo", "bar", "other", false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/other/foo-bar.json")) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); } @Test public void mappingforJsonProperties() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo", "bar", null, false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/foo-bar.json")) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); } @Test public void mappingForLabelledJsonPropertiesWithHyphen() throws Exception { when(EnvironmentControllerTests.this.repository.findOne("foo-bar-foo2-bar2", "spam", "other", false)) - .thenReturn(EnvironmentControllerTests.this.environment); + .thenReturn(EnvironmentControllerTests.this.environment); this.mvc.perform(MockMvcRequestBuilders.get("/other/foo-bar-foo2-bar2-spam.json")) - .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); + .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)); } @@ -658,10 +660,11 @@ class EnvironmentControllerTests { public void handleEnvironmentException() throws Exception { when(EnvironmentControllerTests.this.repository.findOne(eq("exception"), eq("bad_syntax.ext"), any(), eq(false))) - .thenThrow(new FailedToConstructEnvironmentException("Cannot construct", - new RuntimeException("underlier"))); + .thenThrow(new FailedToConstructEnvironmentException("Cannot construct", + new RuntimeException("underlier"))); MvcResult result = this.mvc.perform(MockMvcRequestBuilders.get("/exception/bad_syntax.ext")) - .andExpect(MockMvcResultMatchers.status().is(500)).andReturn(); + .andExpect(MockMvcResultMatchers.status().is(500)) + .andReturn(); assertThat(result.getResponse().getErrorMessage()).isEqualTo("Cannot construct"); } @@ -673,7 +676,7 @@ class EnvironmentControllerTests { @BeforeEach public void initMockMvc() { StandaloneMockMvcBuilder builder = MockMvcBuilders - .standaloneSetup(EnvironmentControllerTests.this.controller); + .standaloneSetup(EnvironmentControllerTests.this.controller); builder.setPatternParser(new PathPatternParser()); this.mvc = builder.build(); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepositoryTests.java index 4a0b8877..8c74a289 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/EnvironmentEncryptorEnvironmentRepositoryTests.java @@ -60,8 +60,11 @@ public class EnvironmentEncryptorEnvironmentRepositoryTests { map.put("a.b.c", "d"); this.environment.add(new PropertySource("one", map)); when(this.repository.findOne("foo", "bar", "master", false)).thenReturn(this.environment); - assertThat(this.controller.findOne("foo", "bar", "master", false).getPropertySources().get(0).getSource() - .toString()).isEqualTo("{foo=bar}"); + assertThat(this.controller.findOne("foo", "bar", "master", false) + .getPropertySources() + .get(0) + .getSource() + .toString()).isEqualTo("{foo=bar}"); } @Test @@ -71,8 +74,11 @@ public class EnvironmentEncryptorEnvironmentRepositoryTests { map.put("bar", "foo"); this.environment.add(new PropertySource("one", map)); when(this.repository.findOne("foo", "bar", "master", false)).thenReturn(this.environment); - assertThat(this.controller.findOne("foo", "bar", "master", false).getPropertySources().get(0).getSource() - .toString()).isEqualTo("{foo=${bar}}"); + assertThat(this.controller.findOne("foo", "bar", "master", false) + .getPropertySources() + .get(0) + .getSource() + .toString()).isEqualTo("{foo=${bar}}"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/GoogleSecretManagerEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/GoogleSecretManagerEnvironmentRepositoryTests.java index 8c3b4758..a6e2682e 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/GoogleSecretManagerEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/GoogleSecretManagerEnvironmentRepositoryTests.java @@ -55,7 +55,8 @@ public class GoogleSecretManagerEnvironmentRepositoryTests { SecretManagerServiceClient mock = mock(SecretManagerServiceClient.class); properties.setVersion(1); assertThat(GoogleSecretManagerAccessStrategyFactory.forVersion(null, null, properties, - mock) instanceof GoogleSecretManagerV1AccessStrategy).isTrue(); + mock) instanceof GoogleSecretManagerV1AccessStrategy) + .isTrue(); } @Test @@ -95,14 +96,22 @@ public class GoogleSecretManagerEnvironmentRepositoryTests { SecretManagerServiceClient mock = mock(SecretManagerServiceClient.class); SecretManagerServiceClient.ListSecretVersionsPagedResponse response = mock( SecretManagerServiceClient.ListSecretVersionsPagedResponse.class); - SecretVersion secret1 = SecretVersion.newBuilder().setName("projects/test-project/secrets/test/versions/1") - .setState(SecretVersion.State.ENABLED).build(); - SecretVersion secret2 = SecretVersion.newBuilder().setName("projects/test-project/secrets/test/versions/4") - .setState(SecretVersion.State.ENABLED).build(); - SecretVersion secret3 = SecretVersion.newBuilder().setName("projects/test-project/secrets/test/versions/9") - .setState(SecretVersion.State.ENABLED).build(); - SecretVersion secret4 = SecretVersion.newBuilder().setName("projects/test-project/secrets/test/versions/12") - .setState(SecretVersion.State.ENABLED).build(); + SecretVersion secret1 = SecretVersion.newBuilder() + .setName("projects/test-project/secrets/test/versions/1") + .setState(SecretVersion.State.ENABLED) + .build(); + SecretVersion secret2 = SecretVersion.newBuilder() + .setName("projects/test-project/secrets/test/versions/4") + .setState(SecretVersion.State.ENABLED) + .build(); + SecretVersion secret3 = SecretVersion.newBuilder() + .setName("projects/test-project/secrets/test/versions/9") + .setState(SecretVersion.State.ENABLED) + .build(); + SecretVersion secret4 = SecretVersion.newBuilder() + .setName("projects/test-project/secrets/test/versions/12") + .setState(SecretVersion.State.ENABLED) + .build(); List secrets = new ArrayList(); secrets.add(secret1); secrets.add(secret2); @@ -128,7 +137,8 @@ public class GoogleSecretManagerEnvironmentRepositoryTests { }; Mockito.doReturn(accessSecretVersionResponse).when(mock).accessSecretVersion(ArgumentMatchers.argThat(matcher)); assertThat(strategy.getSecretValue(Secret.newBuilder().setName("projects/test-project/secrets/test").build(), - new GoogleSecretComparatorByVersion())).isEqualTo("test-value"); + new GoogleSecretComparatorByVersion())) + .isEqualTo("test-value"); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactoryTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactoryTest.java index 482ae566..ec7361cf 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactoryTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/HttpClientConfigurableHttpConnectionFactoryTest.java @@ -67,8 +67,10 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { HttpConnection actualConnection = this.connectionFactory.create(new URL(url)); - HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values().stream() - .findFirst().get(); + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values() + .stream() + .findFirst() + .get(); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -83,8 +85,10 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { HttpConnection actualConnection = this.connectionFactory.create(new URL(url)); - HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values().stream() - .findFirst().get(); + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values() + .stream() + .findFirst() + .get(); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); verify(customizer, times(1)).customize(any(HttpClientBuilder.class)); @@ -99,8 +103,10 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { HttpConnection actualConnection = this.connectionFactory.create(new URL(url + "/some/path.properties")); - HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values().stream() - .findFirst().get(); + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values() + .stream() + .findFirst() + .get(); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -112,10 +118,12 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { this.connectionFactory.addConfiguration(properties); HttpConnection actualConnection = this.connectionFactory - .create(new URL("http://localhost/value-test.git" + "/some/path.properties")); + .create(new URL("http://localhost/value-test.git" + "/some/path.properties")); - HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values().stream() - .findFirst().get(); + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values() + .stream() + .findFirst() + .get(); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -126,11 +134,13 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { properties.setUri("https://localhost/v1/repos/pvvts_configs-{application}"); this.connectionFactory.addConfiguration(properties); - HttpConnection actualConnection = this.connectionFactory.create( - new URL("https://localhost/v1/repos/pvvts_configs-applicationPasswords" + "/some/path.properties")); + HttpConnection actualConnection = this.connectionFactory + .create(new URL("https://localhost/v1/repos/pvvts_configs-applicationPasswords" + "/some/path.properties")); - HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values().stream() - .findFirst().get(); + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values() + .stream() + .findFirst() + .get(); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -147,7 +157,7 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { HttpConnection actualConnection = this.connectionFactory.create(new URL(properties1.getUri())); HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri - .get(properties1.getUri()); + .get(properties1.getUri()); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -164,7 +174,7 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { HttpConnection actualConnection = this.connectionFactory.create(new URL(properties1.getUri())); HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri - .get(properties1.getUri()); + .get(properties1.getUri()); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -182,9 +192,9 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { this.connectionFactory.addConfiguration(properties3); HttpConnection actualConnection = this.connectionFactory - .create(new URL("https://github.com/user/user-MultiApps.git/info/refs?service=git-upload-pack")); + .create(new URL("https://github.com/user/user-MultiApps.git/info/refs?service=git-upload-pack")); HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri - .get(properties2.getUri()); + .get(properties2.getUri()); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -202,7 +212,7 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { new URL(properties2.getUri().replace("{placeholder1}", "value1").replace("{placeholder2}", "value2"))); HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri - .get(properties2.getUri()); + .get(properties2.getUri()); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -232,12 +242,12 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { this.connectionFactory.addConfiguration(properties1); this.connectionFactory.addConfiguration(properties2); - HttpConnection actualConnection = this.connectionFactory.create( - new URL(properties2.getUri().replace("{placeholder1}", "value1").replace("{placeholder2}", "value2") - + "/some/path.properties")); + HttpConnection actualConnection = this.connectionFactory + .create(new URL(properties2.getUri().replace("{placeholder1}", "value1").replace("{placeholder2}", "value2") + + "/some/path.properties")); HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri - .get(properties2.getUri()); + .get(properties2.getUri()); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -249,10 +259,12 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { this.connectionFactory.addConfiguration(properties); HttpConnection actualConnection = this.connectionFactory - .create(new URL("http://server.com/server-test.git" + "/some/path.properties")); + .create(new URL("http://server.com/server-test.git" + "/some/path.properties")); - HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values().stream() - .findFirst().get(); + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values() + .stream() + .findFirst() + .get(); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -264,10 +276,12 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { this.connectionFactory.addConfiguration(properties); HttpConnection actualConnection = this.connectionFactory - .create(new URL("http://server.com/hello-foo/server-test.git" + "/some/path.properties")); + .create(new URL("http://server.com/hello-foo/server-test.git" + "/some/path.properties")); - HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values().stream() - .findFirst().get(); + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values() + .stream() + .findFirst() + .get(); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -279,10 +293,12 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { this.connectionFactory.addConfiguration(properties); HttpConnection actualConnection = this.connectionFactory - .create(new URL("http://localhost/val-testval.git" + "/some/path.properties")); + .create(new URL("http://localhost/val-testval.git" + "/some/path.properties")); - HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values().stream() - .findFirst().get(); + HttpClientBuilder expectedHttpClientBuilder = this.connectionFactory.httpClientBuildersByUri.values() + .stream() + .findFirst() + .get(); HttpClientBuilder actualHttpClientBuilder = getActualHttpClientBuilder(actualConnection); assertThat(actualHttpClientBuilder).isSameAs(expectedHttpClientBuilder); } @@ -300,8 +316,9 @@ public class HttpClientConfigurableHttpConnectionFactoryTest { List closables = (List) ReflectionUtils.getField(closeablesField, actualHttpClient); return closables.stream().map(o -> { Field builderField = Arrays.stream(o.getClass().getDeclaredFields()) - .filter(field -> HttpClientBuilder.class.isAssignableFrom(field.getType())).findFirst() - .orElse(null); + .filter(field -> HttpClientBuilder.class.isAssignableFrom(field.getType())) + .findFirst() + .orElse(null); if (builderField != null) { ReflectionUtils.makeAccessible(builderField); return ReflectionUtils.getField(builderField, o); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitConfigServerTestData.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitConfigServerTestData.java index 261b89dd..38d9fcbb 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitConfigServerTestData.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitConfigServerTestData.java @@ -73,14 +73,19 @@ public class JGitConfigServerTestData { else { clonedRepoDir.mkdirs(); } - Git clonedGit = Git.cloneRepository().setURI("file://" + remoteRepoDir.getAbsolutePath()) - .setDirectory(clonedRepoDir).setBranch("master").setCloneAllBranches(true).call(); + Git clonedGit = Git.cloneRepository() + .setURI("file://" + remoteRepoDir.getAbsolutePath()) + .setDirectory(clonedRepoDir) + .setBranch("master") + .setCloneAllBranches(true) + .call(); // setup our test spring application pointing to the local repo Collection properties = new ArrayList<>(additionalProperties); properties.add("spring.cloud.config.server.git.uri:" + "file://" + clonedRepoDir.getAbsolutePath()); ConfigurableApplicationContext context = new SpringApplicationBuilder(sources).web(WebApplicationType.NONE) - .properties(properties.toArray(new String[0])).run(); + .properties(properties.toArray(new String[0])) + .run(); JGitEnvironmentRepository repository = context.getBean(JGitEnvironmentRepository.class); return new JGitConfigServerTestData(new JGitConfigServerTestData.LocalGit(remoteGit, remoteRepoDir), diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryConcurrencyTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryConcurrencyTests.java index 1b1e25ab..62d9a42a 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryConcurrencyTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryConcurrencyTests.java @@ -100,7 +100,8 @@ public class JGitEnvironmentRepositoryConcurrencyTests { public void vanilla() throws Exception { String uri = ConfigServerTestUtils.prepareLocalRepo(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + uri).run(); + .properties("spring.cloud.config.server.git.uri:" + uri) + .run(); final EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); ExecutorService threads = Executors.newFixedThreadPool(4); List> tasks = new ArrayList>(); @@ -131,7 +132,7 @@ public class JGitEnvironmentRepositoryConcurrencyTests { public void concurrentRefreshContextAndGetLabels() throws Exception { // Prepare the repo final JGitConfigServerTestData testData = JGitConfigServerTestData - .prepareClonedGitRepository(TestConfiguration.class); + .prepareClonedGitRepository(TestConfiguration.class); JGitEnvironmentRepository repository = testData.getRepository(); repository.setCloneOnStart(true); repository.setGitFactory(new DelayedGitFactoryMock()); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryIntegrationTests.java index 3052622f..a898315f 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryIntegrationTests.java @@ -103,7 +103,8 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void vanilla() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + uri).run(); + .properties("spring.cloud.config.server.git.uri:" + uri) + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); @@ -117,9 +118,9 @@ public class JGitEnvironmentRepositoryIntegrationTests { assertThatExceptionOfType(NoSuchLabelException.class).isThrownBy(() -> { String uri = ConfigServerTestUtils.prepareLocalRepo(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + uri, - "spring.cloud.config.server.git.tryMasterBranch:false") - .run(); + .properties("spring.cloud.config.server.git.uri:" + uri, + "spring.cloud.config.server.git.tryMasterBranch:false") + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", null); }); @@ -130,7 +131,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .run("--spring.cloud.config.server.git.uri=" + uri); + .run("--spring.cloud.config.server.git.uri=" + uri); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources().get(0).getSource().get("foo")).isEqualTo("bar"); @@ -171,7 +172,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator().next().getName(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .run("--spring.cloud.config.server.git.uri=" + uri); + .run("--spring.cloud.config.server.git.uri=" + uri); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); @@ -200,7 +201,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { assertThat(conflictingCommit).isEqualTo(locations.getVersion()); assertThat(git.status().call().isClean()).as("Local repository is not cleaned after retrieving resources.") - .isTrue(); + .isTrue(); } @Test @@ -216,8 +217,8 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void nested() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("another-config-repo"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - // TODO: why didn't .properties() work for me? - .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths=sub"); + // TODO: why didn't .properties() work for me? + .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths=sub"); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); @@ -227,9 +228,9 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void nestedWithApplicationPlaceholders() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("nested-repo"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - // TODO: why didn't .properties() work for me? - .run("--spring.cloud.config.server.git.uri=" + uri, - "--spring.cloud.config.server.git.searchPaths={application}"); + // TODO: why didn't .properties() work for me? + .run("--spring.cloud.config.server.git.uri=" + uri, + "--spring.cloud.config.server.git.searchPaths={application}"); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("foo,bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(3); @@ -240,23 +241,23 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void verifyPropertySourceOrdering() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("ordering-repo"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths=**"); + .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths=**"); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("application", "test", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo("file:././target/repos/ordering-repo//project/sub/application-test.yml"); + .isEqualTo("file:././target/repos/ordering-repo//project/sub/application-test.yml"); assertThat(environment.getPropertySources().get(1).getName()) - .isEqualTo("file:././target/repos/ordering-repo//project/application.yml"); + .isEqualTo("file:././target/repos/ordering-repo//project/application.yml"); } @Test public void nestedWithProfilePlaceholders() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("nested-repo"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - // TODO: why didn't .properties() work for me? - .run("--spring.cloud.config.server.git.uri=" + uri, - "--spring.cloud.config.server.git.searchPaths={profile}"); + // TODO: why didn't .properties() work for me? + .run("--spring.cloud.config.server.git.uri=" + uri, + "--spring.cloud.config.server.git.searchPaths={profile}"); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("staging", "foo,bar", "master"); assertThat(environment.getPropertySources()).hasSize(3); @@ -265,20 +266,22 @@ public class JGitEnvironmentRepositoryIntegrationTests { @Test public void singleElementArrayIndexSearchPath() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("nested-repo"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run( - "--spring.cloud.config.server.git.uri=" + uri, - "--spring.cloud.config.server.git.searchPaths[0]={application}"); + this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .run("--spring.cloud.config.server.git.uri=" + uri, + "--spring.cloud.config.server.git.searchPaths[0]={application}"); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); assertThat(repository.getSearchPaths()).containsExactly("{application}"); assertThat(Arrays.equals(repository.getSearchPaths(), new JGitEnvironmentRepository(repository.getEnvironment(), - new JGitEnvironmentProperties(), ObservationRegistry.NOOP).getSearchPaths())).isFalse(); + new JGitEnvironmentProperties(), ObservationRegistry.NOOP) + .getSearchPaths())).isFalse(); } @Test public void defaultLabel() throws Exception { String uri = ConfigServerTestUtils.prepareLocalRepo(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + uri).run(); + .properties("spring.cloud.config.server.git.uri:" + uri) + .run(); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); assertThat(repository.getDefaultLabel()).isEqualTo(JGitEnvironmentProperties.MAIN_LABEL); } @@ -288,7 +291,8 @@ public class JGitEnvironmentRepositoryIntegrationTests { assertThatExceptionOfType(NoSuchLabelException.class).isThrownBy(() -> { String uri = ConfigServerTestUtils.prepareLocalRepo(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + uri).run(); + .properties("spring.cloud.config.server.git.uri:" + uri) + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "unknownlabel"); }); @@ -298,8 +302,8 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void findOne_CloneOnStartTrue_FindOneSuccess() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run( - "--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.cloneOnStart=true"); + this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.cloneOnStart=true"); EnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); assertThat(((JGitEnvironmentRepository) repository).isCloneOnStart()).isTrue(); Environment environment = repository.findOne("bar", "staging", "master"); @@ -313,8 +317,8 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void findOne_FileAddedToRepo_FindOneSuccess() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run( - "--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.cloneOnStart=true"); + this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.cloneOnStart=true"); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources().get(0).getSource().get("foo")).isEqualTo("bar"); @@ -332,9 +336,9 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void findOne_NestedSearchPath_FindOneSuccess() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("another-config-repo"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - // TODO: why didn't .properties() work for me? - .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths=sub", - "--spring.cloud.config.server.git.cloneOnStart=true"); + // TODO: why didn't .properties() work for me? + .run("--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.searchPaths=sub", + "--spring.cloud.config.server.git.cloneOnStart=true"); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); @@ -345,9 +349,9 @@ public class JGitEnvironmentRepositoryIntegrationTests { assertThatExceptionOfType(NoSuchLabelException.class).isThrownBy(() -> { String uri = ConfigServerTestUtils.prepareLocalRepo(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + uri, - "--spring.cloud.config.server.git.cloneOnStart=true") - .run(); + .properties("spring.cloud.config.server.git.uri:" + uri, + "--spring.cloud.config.server.git.cloneOnStart=true") + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "unknownlabel"); }); @@ -356,7 +360,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { @Test public void testVersionUpdate() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData - .prepareClonedGitRepository(TestConfiguration.class); + .prepareClonedGitRepository(TestConfiguration.class); // get our starting versions String startingLocalVersion = getCommitID(testData.getClonedGit().getGit(), "master"); @@ -397,7 +401,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { @Test public void testNewRemoteBranch() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData - .prepareClonedGitRepository(TestConfiguration.class); + .prepareClonedGitRepository(TestConfiguration.class); Environment environment = testData.getRepository().findOne("bar", "staging", "master"); Object fooProperty = ConfigServerTestUtils.getProperty(environment, "bar.properties", "foo"); @@ -422,7 +426,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { @Test public void testNewRemoteTag() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData - .prepareClonedGitRepository(TestConfiguration.class); + .prepareClonedGitRepository(TestConfiguration.class); Git serverGit = testData.getServerGit().getGit(); @@ -462,7 +466,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { @Test public void testNewCommitID() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData - .prepareClonedGitRepository(TestConfiguration.class); + .prepareClonedGitRepository(TestConfiguration.class); // get our starting versions String startingRemoteVersion = getCommitID(testData.getServerGit().getGit(), "master"); @@ -505,7 +509,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { */ public void testNewCommitIDWithRefreshRate() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData - .prepareClonedGitRepository(TestConfiguration.class); + .prepareClonedGitRepository(TestConfiguration.class); // get our starting versions String startingRemoteVersion = getCommitID(testData.getServerGit().getGit(), "master"); @@ -560,7 +564,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void testUnknownLabelWithRemote() throws Exception { assertThatExceptionOfType(NoSuchLabelException.class).isThrownBy(() -> { JGitConfigServerTestData testData = JGitConfigServerTestData - .prepareClonedGitRepository(TestConfiguration.class); + .prepareClonedGitRepository(TestConfiguration.class); testData.getRepository().findOne("bar", "staging", "BADLabel"); }); } @@ -575,9 +579,9 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void passphrase() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("config-repo"); final String passphrase = "thisismypassphrase"; - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run( - "--spring.cloud.config.server.git.uri=" + uri, - "--spring.cloud.config.server.git.passphrase=" + passphrase); + this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .run("--spring.cloud.config.server.git.uri=" + uri, + "--spring.cloud.config.server.git.passphrase=" + passphrase); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); assertThat(repository.getPassphrase()).contains(passphrase); } @@ -586,9 +590,9 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void strictHostKeyChecking() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo("config-repo"); final boolean strictHostKeyChecking = true; - this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE).run( - "--spring.cloud.config.server.git.uri=" + uri, - "--spring.cloud.config.server.git.strict-host-key-checking=" + strictHostKeyChecking); + this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) + .run("--spring.cloud.config.server.git.uri=" + uri, + "--spring.cloud.config.server.git.strict-host-key-checking=" + strictHostKeyChecking); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); assertThat(strictHostKeyChecking).isEqualTo(repository.isStrictHostKeyChecking()); } @@ -597,7 +601,9 @@ public class JGitEnvironmentRepositoryIntegrationTests { public void shouldSetTransportConfigCallback() throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo(); this.context = new SpringApplicationBuilder(TestConfigurationWithTransportConfigCallback.class) - .web(WebApplicationType.NONE).properties("spring.cloud.config.server.git.uri:" + uri).run(); + .web(WebApplicationType.NONE) + .properties("spring.cloud.config.server.git.uri:" + uri) + .run(); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); assertThat(repository.getTransportConfigCallback()).isNotNull(); @@ -606,7 +612,7 @@ public class JGitEnvironmentRepositoryIntegrationTests { @Test public void testShouldReturnEnvironmentFromLocalBranchInCaseRemoteDeleted() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData - .prepareClonedGitRepository(TestConfiguration.class); + .prepareClonedGitRepository(TestConfiguration.class); String branchToDelete = "branchToDelete"; testData.getServerGit().getGit().branchCreate().setName(branchToDelete).call(); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositorySslTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositorySslTests.java index 00b1858c..d40f0554 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositorySslTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositorySslTests.java @@ -74,7 +74,9 @@ public class JGitEnvironmentRepositorySslTests { public void selfSignedCertIsRejected() { assertThatExceptionOfType(CertificateException.class).isThrownBy(() -> { ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class) - .properties(configServerProperties()).web(WebApplicationType.NONE).run(); + .properties(configServerProperties()) + .web(WebApplicationType.NONE) + .run(); JGitEnvironmentRepository repository = context.getBean(JGitEnvironmentRepository.class); @@ -96,8 +98,9 @@ public class JGitEnvironmentRepositorySslTests { @Test public void selfSignedCertWithSkipSslValidationIsAccepted() { ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class) - .properties(configServerProperties("spring.cloud.config.server.git.skipSslValidation=true")) - .web(WebApplicationType.NONE).run(); + .properties(configServerProperties("spring.cloud.config.server.git.skipSslValidation=true")) + .web(WebApplicationType.NONE) + .run(); JGitEnvironmentRepository repository = context.getBean(JGitEnvironmentRepository.class); repository.findOne("bar", "staging", "master"); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryTests.java index 2a3aee03..7ccae2d3 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JGitEnvironmentRepositoryTests.java @@ -133,7 +133,7 @@ public class JGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -145,7 +145,7 @@ public class JGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/sub/application.yml"); + .isEqualTo(this.repository.getUri() + "/sub/application.yml"); assertVersion(environment); } @@ -157,7 +157,7 @@ public class JGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("sub", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/sub/application.yml"); + .isEqualTo(this.repository.getUri() + "/sub/application.yml"); assertVersion(environment); } @@ -176,7 +176,7 @@ public class JGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/sub/application.yml"); + .isEqualTo(this.repository.getUri() + "/sub/application.yml"); assertVersion(environment); } @@ -186,7 +186,7 @@ public class JGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "raw"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -196,7 +196,7 @@ public class JGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "foo"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -206,7 +206,7 @@ public class JGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -218,7 +218,7 @@ public class JGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -1289,7 +1289,7 @@ public class JGitEnvironmentRepositoryTests { // Mock calls on list and checkout commands when(mockListBranchCommand.call()).thenReturn(repositoryRefsList); when(mockCheckoutCommand.call()).thenThrow(new RefNotFoundException("Ref main cannot be resolved")) - .thenReturn(mockMasterRef); + .thenReturn(mockMasterRef); JGitEnvironmentProperties properties = new JGitEnvironmentProperties(); properties.setTryMasterBranch(true); JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, properties, @@ -1340,7 +1340,7 @@ public class JGitEnvironmentRepositoryTests { // Mock calls on list and checkout commands when(mockListBranchCommand.call()).thenReturn(repositoryRefsList); when(mockCheckoutCommand.call()).thenThrow(new RefNotFoundException("Ref main cannot be resolved")) - .thenReturn(mockMasterRef); + .thenReturn(mockMasterRef); JGitEnvironmentProperties properties = new JGitEnvironmentProperties(); properties.setTryMasterBranch(false); JGitEnvironmentRepository envRepository = new JGitEnvironmentRepository(this.environment, properties, diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryConfigurationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryConfigurationTests.java index d8ca64d4..0113e976 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryConfigurationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryConfigurationTests.java @@ -42,24 +42,24 @@ public class JdbcEnvironmentRepositoryConfigurationTests { @Test public void jdbcEnvironmentRepositoryBeansConfiguredWhenDefault() throws IOException { new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class) - .withPropertyValues("spring.profiles.active=test,jdbc", "spring.main.web-application-type=none") - .run(context -> { - assertThat(context).hasSingleBean(JdbcEnvironmentRepositoryFactory.class); - assertThat(context).hasSingleBean(JdbcEnvironmentRepository.class); - assertThat(context).hasSingleBean(JdbcEnvironmentRepository.PropertiesResultSetExtractor.class); - }); + .withPropertyValues("spring.profiles.active=test,jdbc", "spring.main.web-application-type=none") + .run(context -> { + assertThat(context).hasSingleBean(JdbcEnvironmentRepositoryFactory.class); + assertThat(context).hasSingleBean(JdbcEnvironmentRepository.class); + assertThat(context).hasSingleBean(JdbcEnvironmentRepository.PropertiesResultSetExtractor.class); + }); } @Test public void jdbcEnvironmentRepositoryBeansConfiguredWitCustomResultSetExtractor() { new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class) - .withBean(CustomResultSetExtractor.class, CustomResultSetExtractor::new) - .withPropertyValues("spring.profiles.active=test,jdbc", "spring.main.web-application-type=none") - .run(context -> { - assertThat(context).hasSingleBean(JdbcEnvironmentRepositoryFactory.class); - assertThat(context).hasSingleBean(JdbcEnvironmentRepository.class); - assertThat(context).hasSingleBean(CustomResultSetExtractor.class); - }); + .withBean(CustomResultSetExtractor.class, CustomResultSetExtractor::new) + .withPropertyValues("spring.profiles.active=test,jdbc", "spring.main.web-application-type=none") + .run(context -> { + assertThat(context).hasSingleBean(JdbcEnvironmentRepositoryFactory.class); + assertThat(context).hasSingleBean(JdbcEnvironmentRepository.class); + assertThat(context).hasSingleBean(CustomResultSetExtractor.class); + }); } @Test @@ -86,10 +86,10 @@ public class JdbcEnvironmentRepositoryConfigurationTests { ContextConsumer consumer) throws IOException { String uri = ConfigServerTestUtils.prepareLocalRepo(); new WebApplicationContextRunner().withUserConfiguration(TestConfigServerApplication.class) - .withPropertyValues("spring.profiles.active=test,jdbc", "spring.main.web-application-type=none", - "spring.cloud.config.server.git.uri:" + uri, - "spring.cloud.config.server.jdbc.enabled:" + jdbcEnabled) - .run(consumer); + .withPropertyValues("spring.profiles.active=test,jdbc", "spring.main.web-application-type=none", + "spring.cloud.config.server.git.uri:" + uri, + "spring.cloud.config.server.jdbc.enabled:" + jdbcEnabled) + .run(consumer); } private static class CustomResultSetExtractor extends JdbcEnvironmentRepository.PropertiesResultSetExtractor { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java index 7ff0534a..89008342 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/JdbcEnvironmentRepositoryTests.java @@ -53,7 +53,8 @@ public class JdbcEnvironmentRepositoryTests { public void basicProperties() { JdbcEnvironmentProperties properties = new JdbcEnvironmentProperties(); Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), properties, - new JdbcEnvironmentRepository.PropertiesResultSetExtractor()).findOne("foo", "bar", ""); + new JdbcEnvironmentRepository.PropertiesResultSetExtractor()) + .findOne("foo", "bar", ""); assertThat(env.getName()).isEqualTo("foo"); assertThat(env.getProfiles()).isEqualTo(new String[] { "bar" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -72,7 +73,8 @@ public class JdbcEnvironmentRepositoryTests { public void testDefaultProfile() { JdbcEnvironmentProperties properties = new JdbcEnvironmentProperties(); Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), properties, - new JdbcEnvironmentRepository.PropertiesResultSetExtractor()).findOne("foo", "", ""); + new JdbcEnvironmentRepository.PropertiesResultSetExtractor()) + .findOne("foo", "", ""); assertThat(env.getName()).isEqualTo("foo"); assertThat(env.getProfiles()).isEqualTo(new String[] { "default" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -91,7 +93,8 @@ public class JdbcEnvironmentRepositoryTests { public void testProfileNotExist() { JdbcEnvironmentProperties properties = new JdbcEnvironmentProperties(); Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), properties, - new JdbcEnvironmentRepository.PropertiesResultSetExtractor()).findOne("foo", "not_exist", ""); + new JdbcEnvironmentRepository.PropertiesResultSetExtractor()) + .findOne("foo", "not_exist", ""); assertThat(env.getName()).isEqualTo("foo"); assertThat(env.getProfiles()).isEqualTo(new String[] { "not_exist" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -106,7 +109,8 @@ public class JdbcEnvironmentRepositoryTests { public void testApplicationNotExist() { JdbcEnvironmentProperties properties = new JdbcEnvironmentProperties(); Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), properties, - new JdbcEnvironmentRepository.PropertiesResultSetExtractor()).findOne("not_exist", "bar", ""); + new JdbcEnvironmentRepository.PropertiesResultSetExtractor()) + .findOne("not_exist", "bar", ""); assertThat(env.getName()).isEqualTo("not_exist"); assertThat(env.getProfiles()).isEqualTo(new String[] { "bar" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -121,7 +125,8 @@ public class JdbcEnvironmentRepositoryTests { public void testApplicationProfileBothNotExist() { JdbcEnvironmentProperties properties = new JdbcEnvironmentProperties(); Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), properties, - new JdbcEnvironmentRepository.PropertiesResultSetExtractor()).findOne("not_exist", "not_exist", ""); + new JdbcEnvironmentRepository.PropertiesResultSetExtractor()) + .findOne("not_exist", "not_exist", ""); assertThat(env.getName()).isEqualTo("not_exist"); assertThat(env.getProfiles()).isEqualTo(new String[] { "not_exist" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -137,7 +142,8 @@ public class JdbcEnvironmentRepositoryTests { properties.setSqlWithoutProfile( "SELECT MY_KEY, MY_VALUE from MY_PROPERTIES where APPLICATION=? and PROFILE is null and LABEL=?"); Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), properties, - new JdbcEnvironmentRepository.PropertiesResultSetExtractor()).findOne("foo", "bar", ""); + new JdbcEnvironmentRepository.PropertiesResultSetExtractor()) + .findOne("foo", "bar", ""); assertThat(env.getName()).isEqualTo("foo"); assertThat(env.getProfiles()).isEqualTo(new String[] { "bar" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -157,7 +163,8 @@ public class JdbcEnvironmentRepositoryTests { JdbcEnvironmentProperties properties = new JdbcEnvironmentProperties(); properties.setSql("SELECT MY_KEY, MY_VALUE from MY_PROPERTIES where APPLICATION=? and PROFILE=? and LABEL=?"); Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), properties, - new JdbcEnvironmentRepository.PropertiesResultSetExtractor()).findOne("foo", "bar", ""); + new JdbcEnvironmentRepository.PropertiesResultSetExtractor()) + .findOne("foo", "bar", ""); assertThat(env.getName()).isEqualTo("foo"); assertThat(env.getProfiles()).isEqualTo(new String[] { "default", "bar" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -183,7 +190,8 @@ public class JdbcEnvironmentRepositoryTests { properties.setSqlWithoutProfile( "SELECT SHOULD_FAIL from TABLE_NOTEXIST where APPLICATION=? and PROFILE is null and LABEL=?"); Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), properties, - new JdbcEnvironmentRepository.PropertiesResultSetExtractor()).findOne("foo", "bar", ""); + new JdbcEnvironmentRepository.PropertiesResultSetExtractor()) + .findOne("foo", "bar", ""); assertThat(env.getName()).isEqualTo("foo"); assertThat(env.getProfiles()).isEqualTo(new String[] { "bar" }); assertThat(env.getLabel()).isEqualTo("master"); @@ -209,7 +217,8 @@ public class JdbcEnvironmentRepositoryTests { JdbcEnvironmentProperties properties = new JdbcEnvironmentProperties(); properties.setDefaultLabel("main"); Environment env = new JdbcEnvironmentRepository(new JdbcTemplate(this.dataSource), properties, - new JdbcEnvironmentRepository.PropertiesResultSetExtractor()).findOne("foo", "bar", ""); + new JdbcEnvironmentRepository.PropertiesResultSetExtractor()) + .findOne("foo", "bar", ""); assertThat(env.getName()).isEqualTo("foo"); assertThat(env.getProfiles()).isEqualTo(new String[] { "bar" }); assertThat(env.getLabel()).isEqualTo("main"); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests.java index 19a4f2e2..02eda5b0 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests.java @@ -84,7 +84,7 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -93,7 +93,7 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { Environment environment = this.repository.findOne("missing-config-repo", "staging", "master"); assertThat(environment.getPropertySources().size()).as("Wrong property sources: " + environment).isEqualTo(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/application.yml"); + .isEqualTo(this.repository.getUri() + "/application.yml"); assertVersion(environment); } @@ -102,7 +102,7 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { Environment environment = this.repository.findOne("test1-config-repo", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(getUri("*").replace("{application}", "test1-config-repo") + "/application.yml"); + .isEqualTo(getUri("*").replace("{application}", "test1-config-repo") + "/application.yml"); assertVersion(environment); } @@ -111,7 +111,7 @@ public class MultipleJGitEnvironmentApplicationPlaceholderRepositoryTests { Environment environment = this.repository.findOne("test2-config-repo", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(getUri("*").replace("{application}", "test2-config-repo") + "/application.properties"); + .isEqualTo(getUri("*").replace("{application}", "test2-config-repo") + "/application.properties"); assertVersion(environment); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProfilePlaceholderRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProfilePlaceholderRepositoryTests.java index ae75a8f6..c38aed2b 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProfilePlaceholderRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentProfilePlaceholderRepositoryTests.java @@ -88,7 +88,7 @@ public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -107,7 +107,7 @@ public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { Environment environment = this.repository.findOne("application", "test2-config-repo", "master"); assertThat(environment.getPropertySources()).hasSize(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(getUri("*").replace("{profile}", "test2-config-repo") + "/application.properties"); + .isEqualTo(getUri("*").replace("{profile}", "test2-config-repo") + "/application.properties"); assertVersion(environment); } @@ -117,8 +117,8 @@ public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { "master"); assertThat(locations.getLocations().length).isEqualTo(1); assertThat(new File(locations.getLocations()[0].replace("file:", "")).getCanonicalPath()) - .isEqualTo(new File(getUri("*").replace("{profile}", "test2-config-repo").replace("file:", "")) - .getCanonicalPath()); + .isEqualTo(new File(getUri("*").replace("{profile}", "test2-config-repo").replace("file:", "")) + .getCanonicalPath()); } @Test @@ -126,7 +126,7 @@ public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { Locations locations = this.repository.getLocations("application", "not-there,another-not-there", "master"); assertThat(locations.getLocations().length).isEqualTo(1); assertThat(new File(locations.getLocations()[0].replace("file:", "")).getCanonicalPath()) - .isEqualTo(new File(this.repository.getUri().replace("file:", "")).getCanonicalPath()); + .isEqualTo(new File(this.repository.getUri().replace("file:", "")).getCanonicalPath()); } @Test @@ -135,16 +135,16 @@ public class MultipleJGitEnvironmentProfilePlaceholderRepositoryTests { "test1-config-repo,test2-config-repo,missing-config-repo", "master"); assertThat(environment.getPropertySources()).hasSize(1); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(getUri("*").replace("{profile}", "test2-config-repo") + "/application.properties"); + .isEqualTo(getUri("*").replace("{profile}", "test2-config-repo") + "/application.properties"); assertVersion(environment); assertThat(new String[] { "test1-config-repo", "test2-config-repo", "missing-config-repo" }) - .isEqualTo(environment.getProfiles()); + .isEqualTo(environment.getProfiles()); } @SuppressWarnings("unchecked") private JGitEnvironmentRepository getRepository(String uri) { Map repos = (Map) ReflectionTestUtils - .getField(this.repository, "placeholders"); + .getField(this.repository, "placeholders"); return repos.get(uri); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactoryTests.java index 60f44a58..0edf7dad 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryFactoryTests.java @@ -55,11 +55,12 @@ public class MultipleJGitEnvironmentRepositoryFactoryTests { new MultipleJGitEnvironmentProperties.PatternMatchingJGitEnvironmentProperties()); multipleJGitEnvironmentProperties.setRepos(patternMatchingJGitEnvironmentPropertiesMap); MultipleJGitEnvironmentRepository multipleJGitEnvironmentRepository = multipleJGitEnvironmentRepositoryFactory - .build(multipleJGitEnvironmentProperties); + .build(multipleJGitEnvironmentProperties); assertThat(multipleJGitEnvironmentRepository.getGitCredentialsProviderFactory()) - .isSameAs(gitCredentialsProviderFactory); + .isSameAs(gitCredentialsProviderFactory); MultipleJGitEnvironmentRepository.PatternMatchingJGitEnvironmentRepository pattenMatchingGitRepo = multipleJGitEnvironmentRepository - .getRepos().get("pattenMatchingGitRepo1"); + .getRepos() + .get("pattenMatchingGitRepo1"); assertThat(pattenMatchingGitRepo.getGitCredentialsProviderFactory()).isSameAs(gitCredentialsProviderFactory); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryIntegrationTests.java index 21e0123e..d9be93d4 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryIntegrationTests.java @@ -80,7 +80,8 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { public void defaultRepo() throws IOException { String defaultRepoUri = ConfigServerTestUtils.prepareLocalRepo("config-repo"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri).run(); + .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri) + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); @@ -95,7 +96,9 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { repoMapping.put("spring.cloud.config.server.git.repos[test1].pattern", "*test1*"); repoMapping.put("spring.cloud.config.server.git.repos[test1].uri", test1RepoUri); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri).properties(repoMapping).run(); + .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri) + .properties(repoMapping) + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("test1-svc", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); @@ -111,12 +114,14 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { repoMapping.put("spring.cloud.config.server.git.repos[test1].uri", test1RepoUri); repoMapping.put("spring.cloud.config.server.git.refresh-rate", "30"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri).properties(repoMapping).run(); + .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri) + .properties(repoMapping) + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("test1-svc", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(30) - .isEqualTo(((MultipleJGitEnvironmentRepository) repository).getRepos().get("test1").getRefreshRate()); + .isEqualTo(((MultipleJGitEnvironmentRepository) repository).getRepos().get("test1").getRefreshRate()); } @Test @@ -128,7 +133,9 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { repoMapping.put("spring.cloud.config.server.git.repos[test1].pattern", "*/staging"); repoMapping.put("spring.cloud.config.server.git.repos[test1].uri", test1RepoUri); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri).properties(repoMapping).run(); + .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri) + .properties(repoMapping) + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("test1-svc", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); @@ -143,7 +150,9 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { repoMapping.put("spring.cloud.config.server.git.repos[test1].pattern", "*/staging"); repoMapping.put("spring.cloud.config.server.git.repos[test1].uri", test1RepoUri); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri).properties(repoMapping).run(); + .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri) + .properties(repoMapping) + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("test1-svc", "staging,cloud", "master"); assertThat(environment.getPropertySources()).hasSize(2); @@ -160,7 +169,9 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { repoMapping.put("spring.cloud.config.server.git.repos[test1].pattern[2]", "*/staging"); repoMapping.put("spring.cloud.config.server.git.repos[test1].uri", test1RepoUri); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri).properties(repoMapping).run(); + .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri) + .properties(repoMapping) + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("test1-svc", "cloud,staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); @@ -176,7 +187,9 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { Map repoMapping = new LinkedHashMap(); repoMapping.put("spring.cloud.config.server.git.repos.test1-svc.uri", test1RepoUri); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri).properties(repoMapping).run(); + .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri) + .properties(repoMapping) + .run(); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("test1-svc", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); @@ -187,9 +200,9 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { Assertions.assertThatThrownBy(() -> { String defaultRepoUri = ConfigServerTestUtils.prepareLocalRepo("config-repo"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri, - "spring.cloud.config.server.git.basedir:/tmp") - .run(); + .properties("spring.cloud.config.server.git.uri:" + defaultRepoUri, + "spring.cloud.config.server.git.basedir:/tmp") + .run(); }).hasMessageContaining("Cannot write parent"); } @@ -199,9 +212,9 @@ public class MultipleJGitEnvironmentRepositoryIntegrationTests { String test1RepoUri = ConfigServerTestUtils.prepareLocalRepo("test1-config-repo"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .properties("spring.cloud.config.server.git.repos.admin:" + test1RepoUri, - "spring.cloud.config.server.git.uri:" + defaultRepoUri) - .run(); + .properties("spring.cloud.config.server.git.repos.admin:" + test1RepoUri, + "spring.cloud.config.server.git.uri:" + defaultRepoUri) + .run(); MultipleJGitEnvironmentProperties properties = this.context.getBean(MultipleJGitEnvironmentProperties.class); Assertions.assertThat(properties.getRepos()).hasSize(1).containsOnlyKeys("admin"); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryTests.java index fd6016f7..fffc7fad 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/MultipleJGitEnvironmentRepositoryTests.java @@ -93,7 +93,7 @@ public class MultipleJGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -120,7 +120,7 @@ public class MultipleJGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/sub/application.yml"); + .isEqualTo(this.repository.getUri() + "/sub/application.yml"); assertVersion(environment); } @@ -129,7 +129,7 @@ public class MultipleJGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "raw"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -138,7 +138,7 @@ public class MultipleJGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "foo"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -147,7 +147,7 @@ public class MultipleJGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("bar", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -163,7 +163,7 @@ public class MultipleJGitEnvironmentRepositoryTests { Environment environment = this.repository.findOne("test1-svc", "staging", "master"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(getUri("*test1*") + "/test1-svc.properties"); + .isEqualTo(getUri("*test1*") + "/test1-svc.properties"); assertVersion(environment); } @@ -174,7 +174,7 @@ public class MultipleJGitEnvironmentRepositoryTests { assertThat(environment.getLabel()).isEqualTo("raw"); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(this.repository.getUri() + "/bar.properties"); + .isEqualTo(this.repository.getUri() + "/bar.properties"); assertVersion(environment); } @@ -184,7 +184,7 @@ public class MultipleJGitEnvironmentRepositoryTests { assertThat(environment.getLabel()).isEqualTo(JGitEnvironmentProperties.MAIN_LABEL); assertThat(environment.getPropertySources()).hasSize(2); assertThat(environment.getPropertySources().get(0).getName()) - .isEqualTo(getUri("*test1*") + "/test1-svc.properties"); + .isEqualTo(getUri("*test1*") + "/test1-svc.properties"); assertVersion(environment); } @@ -235,20 +235,20 @@ public class MultipleJGitEnvironmentRepositoryTests { this.repository.afterPropertiesSet(); assertThat(repo1Username).as("Repo1 has its own username which should not be overwritten") - .isEqualTo(repo1.getUsername()); + .isEqualTo(repo1.getUsername()); assertThat(repo1Password).as("Repo1 has its own password which should not be overwritten") - .isEqualTo(repo1.getPassword()); + .isEqualTo(repo1.getPassword()); assertThat(multiRepoPassphrase) - .as("Repo1 did not specify a passphrase so this should have been copied from the multi repo") - .isEqualTo(repo1.getPassphrase()); + .as("Repo1 did not specify a passphrase so this should have been copied from the multi repo") + .isEqualTo(repo1.getPassphrase()); assertThat(multiRepoUsername) - .as("Repo2 did not specify a username so this should have been copied from the multi repo") - .isEqualTo(repo2.getUsername()); + .as("Repo2 did not specify a username so this should have been copied from the multi repo") + .isEqualTo(repo2.getUsername()); assertThat(multiRepoPassword) - .as("Repo2 did not specify a username so this should have been copied from the multi repo") - .isEqualTo(repo2.getPassword()); + .as("Repo2 did not specify a username so this should have been copied from the multi repo") + .isEqualTo(repo2.getPassword()); assertThat(repo2Passphrase).as("Repo2 has its own passphrase which should not have been overwritten") - .isEqualTo(repo2.getPassphrase()); + .isEqualTo(repo2.getPassphrase()); } @Test @@ -268,20 +268,20 @@ public class MultipleJGitEnvironmentRepositoryTests { this.repository.setSkipSslValidation(false); this.repository.afterPropertiesSet(); assertThat(repo1.isSkipSslValidation()) - .as("If skip SSL validation is false at multi-repo level, then per-repo settings take priority") - .isFalse(); + .as("If skip SSL validation is false at multi-repo level, then per-repo settings take priority") + .isFalse(); assertThat(repo2.isSkipSslValidation()) - .as("If skip SSL validation is false at multi-repo level, then per-repo settings take priority") - .isTrue(); + .as("If skip SSL validation is false at multi-repo level, then per-repo settings take priority") + .isTrue(); this.repository.setSkipSslValidation(true); this.repository.afterPropertiesSet(); - assertThat(repo1.isSkipSslValidation()).as( - "If explicitly set to skip SSL validation at the multi-repo level, then apply same setting to sub-repos") - .isTrue(); - assertThat(repo2.isSkipSslValidation()).as( - "If explicitly set to skip SSL validation at the multi-repo level, then apply same setting to sub-repos") - .isTrue(); + assertThat(repo1.isSkipSslValidation()) + .as("If explicitly set to skip SSL validation at the multi-repo level, then apply same setting to sub-repos") + .isTrue(); + assertThat(repo2.isSkipSslValidation()) + .as("If explicitly set to skip SSL validation at the multi-repo level, then apply same setting to sub-repos") + .isTrue(); } @Test @@ -313,8 +313,9 @@ public class MultipleJGitEnvironmentRepositoryTests { this.repository.setBasedir(basedir); this.repository.afterPropertiesSet(); - }).isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Basedir does not exist and can not be created:"); + }) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Basedir does not exist and can not be created:"); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryTests.java index 13a2528a..95a74dcd 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/NativeEnvironmentRepositoryTests.java @@ -47,8 +47,9 @@ public class NativeEnvironmentRepositoryTests { @BeforeEach public void init() { ConfigurableApplicationContext context = new SpringApplicationBuilder(NativeEnvironmentRepositoryTests.class) - .properties("logging.level.org.springframework.boot.context.config=TRACE").web(WebApplicationType.NONE) - .run(); + .properties("logging.level.org.springframework.boot.context.config=TRACE") + .web(WebApplicationType.NONE) + .run(); this.repository = new NativeEnvironmentRepository(context.getEnvironment(), new NativeEnvironmentProperties(), ObservationRegistry.NOOP); this.repository.setVersion("myversion"); @@ -86,7 +87,7 @@ public class NativeEnvironmentRepositoryTests { assertThat(environment.getVersion()).as("version was wrong").isEqualTo("myversion"); // gh-1778 property sources has the same name. assertThat(environment.getPropertySources().get(0).getName()) - .isNotEqualTo(environment.getPropertySources().get(1).getName()); + .isNotEqualTo(environment.getPropertySources().get(1).getName()); } @Test @@ -97,7 +98,7 @@ public class NativeEnvironmentRepositoryTests { assertThat(environment.getVersion()).as("version was wrong").isEqualTo("myversion"); // gh-1778 property sources has the same name. assertThat(environment.getPropertySources().get(0).getName()) - .isNotEqualTo(environment.getPropertySources().get(1).getName()); + .isNotEqualTo(environment.getPropertySources().get(1).getName()); } @Test @@ -108,7 +109,7 @@ public class NativeEnvironmentRepositoryTests { assertThat(environment.getVersion()).as("version was wrong").isEqualTo("myversion"); // gh-1778 property sources has the same name. assertThat(environment.getPropertySources().get(0).getName()) - .isNotEqualTo(environment.getPropertySources().get(1).getName()); + .isNotEqualTo(environment.getPropertySources().get(1).getName()); } @Test @@ -316,11 +317,12 @@ public class NativeEnvironmentRepositoryTests { this.repository.setSearchLocations("classpath:/test/bad-syntax"); NativeEnvironmentRepository repo = this.repository; assertThatExceptionOfType(FailedToConstructEnvironmentException.class) - .isThrownBy(() -> repo.findOne("foo", "master", "default")).withMessage( - "Could not construct context for config=foo profile=master label=default includeOrigin=false; nested exception is while constructing a mapping\n" - + " in 'reader', line 1, column 1:\n" + " key: value\n" + " ^\n" - + "found duplicate key key\n" + " in 'reader', line 2, column 1:\n" + " key: value\n" - + " ^\n"); + .isThrownBy(() -> repo.findOne("foo", "master", "default")) + .withMessage( + "Could not construct context for config=foo profile=master label=default includeOrigin=false; nested exception is while constructing a mapping\n" + + " in 'reader', line 1, column 1:\n" + " key: value\n" + " ^\n" + + "found duplicate key key\n" + " in 'reader', line 2, column 1:\n" + " key: value\n" + + " ^\n"); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ObservationEnvironmentRepositoryWrapperTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ObservationEnvironmentRepositoryWrapperTests.java index 93c55a24..0e72d6e4 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ObservationEnvironmentRepositoryWrapperTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/ObservationEnvironmentRepositoryWrapperTests.java @@ -36,9 +36,12 @@ class ObservationEnvironmentRepositoryWrapperTests { wrapper.findOne("foo", "bar", "baz"); - assertThat(registry).hasSingleObservationThat().hasNameEqualTo("spring.cloud.config.environment.find") - .hasBeenStarted().hasBeenStopped().hasLowCardinalityKeyValue("spring.cloud.config.environment.class", - "org.springframework.cloud.config.server.environment.ObservationEnvironmentRepositoryWrapperTests$MyEnvRepo"); + assertThat(registry).hasSingleObservationThat() + .hasNameEqualTo("spring.cloud.config.environment.find") + .hasBeenStarted() + .hasBeenStopped() + .hasLowCardinalityKeyValue("spring.cloud.config.environment.class", + "org.springframework.cloud.config.server.environment.ObservationEnvironmentRepositoryWrapperTests$MyEnvRepo"); } @Test @@ -51,22 +54,26 @@ class ObservationEnvironmentRepositoryWrapperTests { wrapper.findOne("foo", "bar", "baz"); assertThat(registry).hasHandledContextsThatSatisfy(contexts -> { - contexts.stream().filter(context -> context.getName().equals("spring.cloud.config.environment.find") - && contextExists(context, "spring.cloud.config.environment.class", - "org.springframework.cloud.config.server.environment.CompositeEnvironmentRepository")) - .findFirst().orElseThrow( - () -> new AssertionError("There's no observation for the Composite EnvironmentRepository")); - contexts.stream().filter(context -> context.getName().equals("spring.cloud.config.environment.find") - && contextExists(context, "spring.cloud.config.environment.class", - "org.springframework.cloud.config.server.environment.ObservationEnvironmentRepositoryWrapperTests$MyEnvRepo")) - .findFirst().orElseThrow( - () -> new AssertionError("There's no observation for the wrapped EnvironmentRepository")); + contexts.stream() + .filter(context -> context.getName().equals("spring.cloud.config.environment.find") + && contextExists(context, "spring.cloud.config.environment.class", + "org.springframework.cloud.config.server.environment.CompositeEnvironmentRepository")) + .findFirst() + .orElseThrow( + () -> new AssertionError("There's no observation for the Composite EnvironmentRepository")); + contexts.stream() + .filter(context -> context.getName().equals("spring.cloud.config.environment.find") && contextExists( + context, "spring.cloud.config.environment.class", + "org.springframework.cloud.config.server.environment.ObservationEnvironmentRepositoryWrapperTests$MyEnvRepo")) + .findFirst() + .orElseThrow(() -> new AssertionError("There's no observation for the wrapped EnvironmentRepository")); }); } private boolean contextExists(Observation.Context context, String tagName, String tagValue) { - return context.getLowCardinalityKeyValues().stream() - .anyMatch(keyValue -> keyValue.getKey().equals(tagName) && keyValue.getValue().equals(tagValue)); + return context.getLowCardinalityKeyValues() + .stream() + .anyMatch(keyValue -> keyValue.getKey().equals(tagName) && keyValue.getValue().equals(tagValue)); } static class MyEnvRepo implements EnvironmentRepository { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/PassthruEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/PassthruEnvironmentRepositoryTests.java index e0da56a1..5bc92bd2 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/PassthruEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/PassthruEnvironmentRepositoryTests.java @@ -35,8 +35,9 @@ public class PassthruEnvironmentRepositoryTests { public void originTrackedPropertySourceWithoutOriginWorks() { MockEnvironment mockEnvironment = new MockEnvironment(); mockEnvironment.setProperty("normalKey", "normalValue"); - mockEnvironment.getPropertySources().addFirst(new OriginTrackedMapPropertySource("myorigintrackedsource", - Collections.singletonMap("keyNoOrigin", "valueNoOrigin"))); + mockEnvironment.getPropertySources() + .addFirst(new OriginTrackedMapPropertySource("myorigintrackedsource", + Collections.singletonMap("keyNoOrigin", "valueNoOrigin"))); PassthruEnvironmentRepository repository = new PassthruEnvironmentRepository(mockEnvironment); Environment environment = repository.findOne("testapp", "default", "master", true); assertThat(environment).isNotNull(); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryIntegrationTests.java index 1c0a2257..b353849b 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryIntegrationTests.java @@ -78,7 +78,8 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { public void vanilla() throws Exception { String uri = ConfigServerTestUtils.prepareLocalSvnRepo("src/test/resources/svn-config-repo", "target/config"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .profiles("subversion").run("--spring.cloud.config.server.svn.uri=" + uri); + .profiles("subversion") + .run("--spring.cloud.config.server.svn.uri=" + uri); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "trunk"); assertThat(environment.getPropertySources()).hasSize(2); @@ -88,7 +89,8 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { public void update() throws Exception { String uri = ConfigServerTestUtils.prepareLocalSvnRepo("src/test/resources/svn-config-repo", "target/config"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .profiles("subversion").run("--spring.cloud.config.server.svn.uri=" + uri); + .profiles("subversion") + .run("--spring.cloud.config.server.svn.uri=" + uri); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "trunk"); assertThat(environment.getPropertySources().get(0).getSource().get("foo")).isEqualTo("bar"); @@ -118,7 +120,8 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { public void defaultLabel() throws Exception { String uri = ConfigServerTestUtils.prepareLocalSvnRepo("src/test/resources/svn-config-repo", "target/config"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .profiles("subversion").run("--spring.cloud.config.server.svn.uri=" + uri); + .profiles("subversion") + .run("--spring.cloud.config.server.svn.uri=" + uri); SvnKitEnvironmentRepository repository = this.context.getBean(SvnKitEnvironmentRepository.class); assertThat(repository.getDefaultLabel()).isEqualTo("trunk"); } @@ -129,7 +132,8 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { String uri = ConfigServerTestUtils.prepareLocalSvnRepo("src/test/resources/svn-config-repo", "target/config"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .profiles("subversion").run("--spring.cloud.config.server.svn.uri=" + uri); + .profiles("subversion") + .run("--spring.cloud.config.server.svn.uri=" + uri); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "unknownlabel"); assertThat(environment.getPropertySources()).isEmpty(); @@ -140,7 +144,8 @@ public class SVNKitEnvironmentRepositoryIntegrationTests { public void branchLabel() throws Exception { String uri = ConfigServerTestUtils.prepareLocalSvnRepo("src/test/resources/svn-config-repo", "target/config"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(WebApplicationType.NONE) - .profiles("subversion").run("--spring.cloud.config.server.svn.uri=" + uri); + .profiles("subversion") + .run("--spring.cloud.config.server.svn.uri=" + uri); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); Environment environment = repository.findOne("bar", "staging", "demobranch"); assertThat(environment.getPropertySources().get(0).getName()).contains("bar.properties"); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryTests.java index c64c2906..22cc50e1 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/SVNKitEnvironmentRepositoryTests.java @@ -148,7 +148,8 @@ public class SVNKitEnvironmentRepositoryTests { FileUtils.delete(basedir, FileUtils.RECURSIVE | FileUtils.RETRY); } new SpringApplicationBuilder(TestApplication.class).profiles("subversion") - .properties("server.port=8888", "spring.cloud.config.server.svn.uri:" + uri).run(args); + .properties("server.port=8888", "spring.cloud.config.server.svn.uri:" + uri) + .run(args); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java index db500296..a1ec12aa 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryIntegrationTests.java @@ -57,7 +57,7 @@ public class VaultEnvironmentRepositoryIntegrationTests { request, new EnvironmentWatch.Default(), Optional.of(new HttpClientVaultRestTemplateFactory()), withTokenProvider(request)); VaultEnvironmentRepository vaultEnvironmentRepository = vaultEnvironmentRepositoryFactory - .build(withEnvironmentProperties(false)); + .build(withEnvironmentProperties(false)); vaultEnvironmentRepository.findOne("application", "profile", "label"); }).hasCauseInstanceOf(SSLHandshakeException.class); } @@ -69,7 +69,7 @@ public class VaultEnvironmentRepositoryIntegrationTests { request, new EnvironmentWatch.Default(), Optional.of(new HttpClientVaultRestTemplateFactory()), withTokenProvider(request)); VaultEnvironmentRepository vaultEnvironmentRepository = vaultEnvironmentRepositoryFactory - .build(withEnvironmentProperties(true)); + .build(withEnvironmentProperties(true)); Environment actual = vaultEnvironmentRepository.findOne("application", "profile", "label"); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java index 6e2f08d9..2f91f1df 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultEnvironmentRepositoryTests.java @@ -72,7 +72,8 @@ public class VaultEnvironmentRepositoryTests { when(myAppVaultResp.getData()).thenReturn("{\"foo\":\"bar\"}"); when(myAppResp.getBody()).thenReturn(myAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("myapp"))).thenReturn(myAppResp); + eq(VaultResponse.class), eq("myapp"))) + .thenReturn(myAppResp); ResponseEntity appResp = mock(ResponseEntity.class); when(appResp.getStatusCode()).thenReturn(HttpStatus.OK); @@ -80,27 +81,28 @@ public class VaultEnvironmentRepositoryTests { when(appVaultResp.getData()).thenReturn("{\"def-foo\":\"def-bar\"}"); when(appResp.getBody()).thenReturn(appVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("application"))).thenReturn(appResp); + eq(VaultResponse.class), eq("application"))) + .thenReturn(appResp); VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockHttpRequest(), new EnvironmentWatch.Default(), rest, new VaultEnvironmentProperties(), mockTokenProvider()); Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); - assertThat(e.getPropertySources().size()).as( - "Properties for specified application and default application with key 'application' should be returned") - .isEqualTo(2); + assertThat(e.getPropertySources().size()) + .as("Properties for specified application and default application with key 'application' should be returned") + .isEqualTo(2); Map firstResult = new HashMap<>(); firstResult.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for specified application should be returned in priority position") - .isEqualTo(firstResult); + .as("Properties for specified application should be returned in priority position") + .isEqualTo(firstResult); Map secondResult = new HashMap<>(); secondResult.put("def-foo", "def-bar"); assertThat(e.getPropertySources().get(1).getSource()) - .as("Properties for default application with key 'application' should be returned in second position") - .isEqualTo(secondResult); + .as("Properties for default application with key 'application' should be returned in second position") + .isEqualTo(secondResult); } @Test @@ -114,7 +116,8 @@ public class VaultEnvironmentRepositoryTests { when(myAppVaultResp.getData()).thenReturn("{\"foo\":\"bar\"}"); when(myAppResp.getBody()).thenReturn(myAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/foo/bar/secret/{key}"), eq(HttpMethod.GET), - any(HttpEntity.class), eq(VaultResponse.class), eq("myapp"))).thenReturn(myAppResp); + any(HttpEntity.class), eq(VaultResponse.class), eq("myapp"))) + .thenReturn(myAppResp); ResponseEntity appResp = mock(ResponseEntity.class); when(appResp.getStatusCode()).thenReturn(HttpStatus.OK); @@ -122,7 +125,8 @@ public class VaultEnvironmentRepositoryTests { when(appVaultResp.getData()).thenReturn("{\"def-foo\":\"def-bar\"}"); when(appResp.getBody()).thenReturn(appVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/foo/bar/secret/{key}"), eq(HttpMethod.GET), - any(HttpEntity.class), eq(VaultResponse.class), eq("application"))).thenReturn(appResp); + any(HttpEntity.class), eq(VaultResponse.class), eq("application"))) + .thenReturn(appResp); VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); properties.setBackend("foo/bar/secret"); @@ -132,20 +136,20 @@ public class VaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); - assertThat(e.getPropertySources().size()).as( - "Properties for specified application and default application with key 'application' should be returned") - .isEqualTo(2); + assertThat(e.getPropertySources().size()) + .as("Properties for specified application and default application with key 'application' should be returned") + .isEqualTo(2); Map firstResult = new HashMap<>(); firstResult.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for specified application should be returned in priority position") - .isEqualTo(firstResult); + .as("Properties for specified application should be returned in priority position") + .isEqualTo(firstResult); Map secondResult = new HashMap<>(); secondResult.put("def-foo", "def-bar"); assertThat(e.getPropertySources().get(1).getSource()) - .as("Properties for default application with key 'application' should be returned in second position") - .isEqualTo(secondResult); + .as("Properties for default application with key 'application' should be returned in second position") + .isEqualTo(secondResult); } @Test @@ -159,7 +163,8 @@ public class VaultEnvironmentRepositoryTests { when(myAppVaultResp.getData()).thenReturn("{\"foo\":\"bar\"}"); when(myAppResp.getBody()).thenReturn(myAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("myapp"))).thenReturn(myAppResp); + eq(VaultResponse.class), eq("myapp"))) + .thenReturn(myAppResp); ResponseEntity myDefaultKeyResp = mock(ResponseEntity.class); when(myDefaultKeyResp.getStatusCode()).thenReturn(HttpStatus.OK); @@ -167,7 +172,8 @@ public class VaultEnvironmentRepositoryTests { when(myDefaultKeyVaultResp.getData()).thenReturn("{\"def-foo\":\"def-bar\"}"); when(myDefaultKeyResp.getBody()).thenReturn(myDefaultKeyVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("mydefaultkey"))).thenReturn(myDefaultKeyResp); + eq(VaultResponse.class), eq("mydefaultkey"))) + .thenReturn(myDefaultKeyResp); VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockHttpRequest(), new EnvironmentWatch.Default(), rest, new VaultEnvironmentProperties(), mockTokenProvider()); @@ -175,21 +181,21 @@ public class VaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); - assertThat(e.getPropertySources().size()).as( - "Properties for specified application and default application with key 'mydefaultkey' should be returned") - .isEqualTo(2); + assertThat(e.getPropertySources().size()) + .as("Properties for specified application and default application with key 'mydefaultkey' should be returned") + .isEqualTo(2); Map firstResult = new HashMap<>(); firstResult.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for specified application should be returned in priority position") - .isEqualTo(firstResult); + .as("Properties for specified application should be returned in priority position") + .isEqualTo(firstResult); Map secondResult = new HashMap<>(); secondResult.put("def-foo", "def-bar"); assertThat(e.getPropertySources().get(1).getSource()) - .as("Properties for default application with key 'mydefaultkey' should be returned in second position") - .isEqualTo(secondResult); + .as("Properties for default application with key 'mydefaultkey' should be returned in second position") + .isEqualTo(secondResult); } @Test @@ -203,7 +209,8 @@ public class VaultEnvironmentRepositoryTests { when(myAppVaultResp.getData()).thenReturn("{\"myapp-foo\":\"myapp-bar\"}"); when(myAppResp.getBody()).thenReturn(myAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("myapp"))).thenReturn(myAppResp); + eq(VaultResponse.class), eq("myapp"))) + .thenReturn(myAppResp); ResponseEntity yourAppResp = mock(ResponseEntity.class); when(yourAppResp.getStatusCode()).thenReturn(HttpStatus.OK); @@ -211,7 +218,8 @@ public class VaultEnvironmentRepositoryTests { when(yourAppVaultResp.getData()).thenReturn("{\"yourapp-foo\":\"yourapp-bar\"}"); when(yourAppResp.getBody()).thenReturn(yourAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("yourapp"))).thenReturn(yourAppResp); + eq(VaultResponse.class), eq("yourapp"))) + .thenReturn(yourAppResp); ResponseEntity myDefaultKeyResp = mock(ResponseEntity.class); when(myDefaultKeyResp.getStatusCode()).thenReturn(HttpStatus.OK); @@ -219,7 +227,8 @@ public class VaultEnvironmentRepositoryTests { when(myDefaultKeyVaultResp.getData()).thenReturn("{\"def-foo\":\"def-bar\"}"); when(myDefaultKeyResp.getBody()).thenReturn(myDefaultKeyVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("mydefaultkey"))).thenReturn(myDefaultKeyResp); + eq(VaultResponse.class), eq("mydefaultkey"))) + .thenReturn(myDefaultKeyResp); VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockHttpRequest(), new EnvironmentWatch.Default(), rest, new VaultEnvironmentProperties(), mockTokenProvider()); @@ -227,27 +236,27 @@ public class VaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp,yourapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp,yourapp"); - assertThat(e.getPropertySources().size()).as( - "Properties for specified applications and default application with key 'mydefaultkey' should be returned") - .isEqualTo(3); + assertThat(e.getPropertySources().size()) + .as("Properties for specified applications and default application with key 'mydefaultkey' should be returned") + .isEqualTo(3); Map firstResult = new HashMap<>(); firstResult.put("yourapp-foo", "yourapp-bar"); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for first specified application should be returned in priority position") - .isEqualTo(firstResult); + .as("Properties for first specified application should be returned in priority position") + .isEqualTo(firstResult); Map secondResult = new HashMap<>(); secondResult.put("myapp-foo", "myapp-bar"); assertThat(e.getPropertySources().get(1).getSource()) - .as("Properties for second specified application should be returned in priority position") - .isEqualTo(secondResult); + .as("Properties for second specified application should be returned in priority position") + .isEqualTo(secondResult); Map thirdResult = new HashMap<>(); thirdResult.put("def-foo", "def-bar"); assertThat(e.getPropertySources().get(2).getSource()) - .as("Properties for default application with key 'mydefaultkey' should be returned in second position") - .isEqualTo(thirdResult); + .as("Properties for default application with key 'mydefaultkey' should be returned in second position") + .isEqualTo(thirdResult); } @Test @@ -261,7 +270,8 @@ public class VaultEnvironmentRepositoryTests { when(myAppVaultResp.getData()).thenReturn("{\"foo\":\"bar\"}"); when(myAppResp.getBody()).thenReturn(myAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("myapp"))).thenReturn(myAppResp); + eq(VaultResponse.class), eq("myapp"))) + .thenReturn(myAppResp); ResponseEntity appResp = mock(ResponseEntity.class); when(appResp.getStatusCode()).thenReturn(HttpStatus.OK); @@ -269,7 +279,8 @@ public class VaultEnvironmentRepositoryTests { when(appVaultResp.getData()).thenReturn("{\"def-foo\":\"def-bar\"}"); when(appResp.getBody()).thenReturn(appVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("application"))).thenReturn(appResp); + eq(VaultResponse.class), eq("application"))) + .thenReturn(appResp); VaultEnvironmentRepository repo = new VaultEnvironmentRepository(mockHttpRequest(), new EnvironmentWatch.Default(), rest, new VaultEnvironmentProperties(), mockTokenProvider()); @@ -278,12 +289,13 @@ public class VaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); assertThat(e.getPropertySources().size()).as("Only properties for specified application should be returned") - .isEqualTo(1); + .isEqualTo(1); Map result = new HashMap<>(); result.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties should be returned for specified application").isEqualTo(result); + .as("Properties should be returned for specified application") + .isEqualTo(result); } @Test @@ -309,14 +321,16 @@ public class VaultEnvironmentRepositoryTests { VaultResponse myAppVaultResp = getVaultResponse("{\"data\": {\"data\": {\"foo\": \"bar\"}}}"); when(myAppResp.getBody()).thenReturn(myAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/data/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("myapp"))).thenReturn(myAppResp); + eq(VaultResponse.class), eq("myapp"))) + .thenReturn(myAppResp); ResponseEntity appResp = mock(ResponseEntity.class); when(appResp.getStatusCode()).thenReturn(HttpStatus.OK); VaultResponse appVaultResp = getVaultResponse("{\"data\": {\"data\": {\"def-foo\":\"def-bar\"}}}"); when(appResp.getBody()).thenReturn(appVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/data/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("application"))).thenReturn(appResp); + eq(VaultResponse.class), eq("application"))) + .thenReturn(appResp); final VaultEnvironmentProperties vaultEnvironmentProperties = new VaultEnvironmentProperties(); vaultEnvironmentProperties.setKvVersion(2); @@ -325,14 +339,14 @@ public class VaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); - assertThat(e.getPropertySources().size()).as( - "Properties for specified application and default application with key 'application' should be returned") - .isEqualTo(2); + assertThat(e.getPropertySources().size()) + .as("Properties for specified application and default application with key 'application' should be returned") + .isEqualTo(2); Map firstResult = new HashMap<>(); firstResult.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for specified application should be returned in priority position") - .isEqualTo(firstResult); + .as("Properties for specified application should be returned in priority position") + .isEqualTo(firstResult); } @Test @@ -345,14 +359,16 @@ public class VaultEnvironmentRepositoryTests { VaultResponse myAppVaultResp = getVaultResponse("{\"data\": {\"data\": {\"foo\": \"bar\"}}}"); when(myAppResp.getBody()).thenReturn(myAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/data/myorg/{key}"), eq(HttpMethod.GET), - any(HttpEntity.class), eq(VaultResponse.class), eq("myapp"))).thenReturn(myAppResp); + any(HttpEntity.class), eq(VaultResponse.class), eq("myapp"))) + .thenReturn(myAppResp); ResponseEntity appResp = mock(ResponseEntity.class); when(appResp.getStatusCode()).thenReturn(HttpStatus.OK); VaultResponse appVaultResp = getVaultResponse("{\"data\": {\"data\": {\"def-foo\":\"def-bar\"}}}"); when(appResp.getBody()).thenReturn(appVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/data/myorg/{key}"), eq(HttpMethod.GET), - any(HttpEntity.class), eq(VaultResponse.class), eq("application"))).thenReturn(appResp); + any(HttpEntity.class), eq(VaultResponse.class), eq("application"))) + .thenReturn(appResp); final VaultEnvironmentProperties vaultEnvironmentProperties = new VaultEnvironmentProperties(); vaultEnvironmentProperties.setKvVersion(2); @@ -362,14 +378,14 @@ public class VaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); - assertThat(e.getPropertySources().size()).as( - "Properties for specified application and default application with key 'application' should be returned") - .isEqualTo(2); + assertThat(e.getPropertySources().size()) + .as("Properties for specified application and default application with key 'application' should be returned") + .isEqualTo(2); Map firstResult = new HashMap<>(); firstResult.put("foo", "bar"); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for specified application should be returned in priority position") - .isEqualTo(firstResult); + .as("Properties for specified application should be returned in priority position") + .isEqualTo(firstResult); } @Test @@ -383,7 +399,8 @@ public class VaultEnvironmentRepositoryTests { when(myAppVaultResp.getData()).thenReturn("{\"foo\":\"bar\"}"); when(myAppResp.getBody()).thenReturn(myAppVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("myapp"))).thenReturn(myAppResp); + eq(VaultResponse.class), eq("myapp"))) + .thenReturn(myAppResp); ResponseEntity appResp = mock(ResponseEntity.class); when(appResp.getStatusCode()).thenReturn(HttpStatus.OK); @@ -391,7 +408,8 @@ public class VaultEnvironmentRepositoryTests { when(appVaultResp.getData()).thenReturn("{\"def-foo\":\"def-bar\"}"); when(appResp.getBody()).thenReturn(appVaultResp); when(rest.exchange(eq("http://127.0.0.1:8200/v1/secret/{key}"), eq(HttpMethod.GET), any(HttpEntity.class), - eq(VaultResponse.class), eq("application"))).thenReturn(appResp); + eq(VaultResponse.class), eq("application"))) + .thenReturn(appResp); VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); properties.setNamespace("mynamespace"); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactoryTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactoryTest.java index b55c788b..981e9ca4 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactoryTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/VaultKvAccessStrategyFactoryTest.java @@ -44,7 +44,7 @@ public class VaultKvAccessStrategyFactoryTest { @Test public void testGetUnsupportedStrategy() { Assertions.assertThatThrownBy(() -> VaultKvAccessStrategyFactory.forVersion(null, "foo", 0, "")) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultClientConfigurationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultClientConfigurationTests.java index 2adf22d2..caa7baa8 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultClientConfigurationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultClientConfigurationTests.java @@ -156,9 +156,9 @@ class SpringVaultClientConfigurationTests { assertClientAuthenticationOfType(properties, AzureMsiAuthentication.class); AzureMsiAuthentication clientAuthentication = (AzureMsiAuthentication) getConfiguration(properties) - .clientAuthentication(); + .clientAuthentication(); AzureMsiAuthenticationOptions options = (AzureMsiAuthenticationOptions) ReflectionTestUtils - .getField(clientAuthentication, "options"); + .getField(clientAuthentication, "options"); assertThat(options.getIdentityTokenServiceUri()).isEqualTo(DEFAULT_IDENTITY_TOKEN_SERVICE_URI); assertThat(options.getInstanceMetadataServiceUri()).isEqualTo(DEFAULT_INSTANCE_METADATA_SERVICE_URI); @@ -347,11 +347,13 @@ class SpringVaultClientConfigurationTests { @SuppressWarnings("deprecation") public void springVaultClientConfigurationIsAProxy() { new WebApplicationContextRunner().withPropertyValues("spring.profiles.active=vault") - .withConfiguration(UserConfigurations.of(ConfigServerConfiguration.class)) - .withConfiguration(AutoConfigurations.of(ConfigServerAutoConfiguration.class)).run(context -> { - assertThat(context).getBean(SpringVaultClientConfiguration.class).isNotNull() - .matches(svcc -> ClassUtils.isCglibProxyClassName(svcc.getClass().getName()), "is a proxy"); - }); + .withConfiguration(UserConfigurations.of(ConfigServerConfiguration.class)) + .withConfiguration(AutoConfigurations.of(ConfigServerAutoConfiguration.class)) + .run(context -> { + assertThat(context).getBean(SpringVaultClientConfiguration.class) + .isNotNull() + .matches(svcc -> ClassUtils.isCglibProxyClassName(svcc.getClass().getName()), "is a proxy"); + }); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultEnvironmentRepositoryFactoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultEnvironmentRepositoryFactoryTests.java index 562b780b..17c2d1de 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultEnvironmentRepositoryFactoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultEnvironmentRepositoryFactoryTests.java @@ -42,7 +42,8 @@ public class SpringVaultEnvironmentRepositoryFactoryTests { VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); SpringVaultEnvironmentRepository environmentRepository = new SpringVaultEnvironmentRepositoryFactory( - mockHttpRequest(), new EnvironmentWatch.Default(), mockClientConfiguration()).build(properties); + mockHttpRequest(), new EnvironmentWatch.Default(), mockClientConfiguration()) + .build(properties); VaultKeyValueOperations keyValueTemplate = environmentRepository.getKeyValueTemplate(); assertThat(keyValueTemplate.getApiVersion()).isEqualTo(VaultKeyValueOperationsSupport.KeyValueBackend.KV_1); @@ -54,7 +55,8 @@ public class SpringVaultEnvironmentRepositoryFactoryTests { properties.setKvVersion(2); SpringVaultEnvironmentRepository environmentRepository = new SpringVaultEnvironmentRepositoryFactory( - mockHttpRequest(), new EnvironmentWatch.Default(), mockClientConfiguration()).build(properties); + mockHttpRequest(), new EnvironmentWatch.Default(), mockClientConfiguration()) + .build(properties); VaultKeyValueOperations keyValueTemplate = environmentRepository.getKeyValueTemplate(); assertThat(keyValueTemplate.getApiVersion()).isEqualTo(VaultKeyValueOperationsSupport.KeyValueBackend.KV_2); diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultEnvironmentRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultEnvironmentRepositoryTests.java index 74760449..cdcdf26b 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultEnvironmentRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/SpringVaultEnvironmentRepositoryTests.java @@ -77,16 +77,16 @@ public class SpringVaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); - assertThat(e.getPropertySources()).as( - "Properties for specified application and default application with key 'application' should be returned") - .hasSize(2); + assertThat(e.getPropertySources()) + .as("Properties for specified application and default application with key 'application' should be returned") + .hasSize(2); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for specified application should be returned in priority position") - .containsOnly((Map.Entry) entry("foo", "bar")); + .as("Properties for specified application should be returned in priority position") + .containsOnly((Map.Entry) entry("foo", "bar")); assertThat(e.getPropertySources().get(1).getSource()) - .as("Properties for default application with key 'application' should be returned in second position") - .containsOnly((Map.Entry) entry("def-foo", "def-bar")); + .as("Properties for default application with key 'application' should be returned in second position") + .containsOnly((Map.Entry) entry("def-foo", "def-bar")); } @Test @@ -103,16 +103,16 @@ public class SpringVaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); - assertThat(e.getPropertySources()).as( - "Properties for specified application and default application with key 'application' should be returned") - .hasSize(2); + assertThat(e.getPropertySources()) + .as("Properties for specified application and default application with key 'application' should be returned") + .hasSize(2); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for specified application should be returned in priority position") - .containsOnly((Map.Entry) entry("foo", "bar")); + .as("Properties for specified application should be returned in priority position") + .containsOnly((Map.Entry) entry("foo", "bar")); assertThat(e.getPropertySources().get(1).getSource()) - .as("Properties for default application with key 'application' should be returned in second position") - .containsOnly((Map.Entry) entry("def-foo", "def-bar")); + .as("Properties for default application with key 'application' should be returned in second position") + .containsOnly((Map.Entry) entry("def-foo", "def-bar")); } @Test @@ -127,16 +127,16 @@ public class SpringVaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); - assertThat(e.getPropertySources()).as( - "Properties for specified application and default application with key 'mydefaultkey' should be returned") - .hasSize(2); + assertThat(e.getPropertySources()) + .as("Properties for specified application and default application with key 'mydefaultkey' should be returned") + .hasSize(2); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for specified application should be returned in priority position") - .containsOnly((Map.Entry) entry("foo", "bar")); + .as("Properties for specified application should be returned in priority position") + .containsOnly((Map.Entry) entry("foo", "bar")); assertThat(e.getPropertySources().get(1).getSource()) - .as("Properties for default application with key 'mydefaultkey' should be returned in second position") - .containsOnly((Map.Entry) entry("def-foo", "def-bar")); + .as("Properties for default application with key 'mydefaultkey' should be returned in second position") + .containsOnly((Map.Entry) entry("def-foo", "def-bar")); } @Test @@ -152,21 +152,21 @@ public class SpringVaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp,yourapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp,yourapp"); - assertThat(e.getPropertySources()).as( - "Properties for specified applications and default application with key 'mydefaultkey' should be returned") - .hasSize(3); + assertThat(e.getPropertySources()) + .as("Properties for specified applications and default application with key 'mydefaultkey' should be returned") + .hasSize(3); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for first specified application should be returned in priority position") - .containsOnly((Map.Entry) entry("yourapp-foo", "yourapp-bar")); + .as("Properties for first specified application should be returned in priority position") + .containsOnly((Map.Entry) entry("yourapp-foo", "yourapp-bar")); assertThat(e.getPropertySources().get(1).getSource()) - .as("Properties for second specified application should be returned in priority position") - .containsOnly((Map.Entry) entry("myapp-foo", "myapp-bar")); + .as("Properties for second specified application should be returned in priority position") + .containsOnly((Map.Entry) entry("myapp-foo", "myapp-bar")); assertThat(e.getPropertySources().get(2).getSource()) - .as("Properties for default application with key 'mydefaultkey' should be returned in second position") - .containsOnly((Map.Entry) entry("def-foo", "def-bar")); + .as("Properties for default application with key 'mydefaultkey' should be returned in second position") + .containsOnly((Map.Entry) entry("def-foo", "def-bar")); } @Test @@ -182,11 +182,11 @@ public class SpringVaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); assertThat(e.getPropertySources()).as("Only properties for specified application should be returned") - .hasSize(1); + .hasSize(1); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties should be returned for specified application") - .containsOnly((Map.Entry) entry("foo", "bar")); + .as("Properties should be returned for specified application") + .containsOnly((Map.Entry) entry("foo", "bar")); } @Test @@ -202,13 +202,13 @@ public class SpringVaultEnvironmentRepositoryTests { Environment e = repo.findOne("myapp", null, null); assertThat(e.getName()).as("Name should be the same as the application argument").isEqualTo("myapp"); - assertThat(e.getPropertySources()).as( - "Properties for specified application and default application with key 'application' should be returned") - .hasSize(2); + assertThat(e.getPropertySources()) + .as("Properties for specified application and default application with key 'application' should be returned") + .hasSize(2); assertThat(e.getPropertySources().get(0).getSource()) - .as("Properties for specified application should be returned in priority position") - .containsOnly((Map.Entry) entry("foo", "bar")); + .as("Properties for specified application should be returned in priority position") + .containsOnly((Map.Entry) entry("foo", "bar")); } private VaultResponse withVaultResponse(String key, Object value) { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/authentication/AppRoleClientAuthenticationProviderTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/authentication/AppRoleClientAuthenticationProviderTests.java index 2f62d41a..2e5dfffc 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/authentication/AppRoleClientAuthenticationProviderTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/environment/vault/authentication/AppRoleClientAuthenticationProviderTests.java @@ -37,7 +37,7 @@ class AppRoleClientAuthenticationProviderTests { properties.getAppRole().setSecretId("bar"); AppRoleAuthenticationOptions options = AppRoleClientAuthenticationProvider - .getAppRoleAuthenticationOptions(properties); + .getAppRoleAuthenticationOptions(properties); assertThat(options.getRoleId()).isInstanceOf(RoleId.provided("foo").getClass()); assertThat(options.getSecretId()).isInstanceOf(SecretId.provided("bar").getClass()); @@ -50,7 +50,7 @@ class AppRoleClientAuthenticationProviderTests { properties.getAppRole().setRoleId("foo"); AppRoleAuthenticationOptions options = AppRoleClientAuthenticationProvider - .getAppRoleAuthenticationOptions(properties); + .getAppRoleAuthenticationOptions(properties); assertThat(options.getRoleId()).isInstanceOf(RoleId.provided("foo").getClass()); assertThat(options.getSecretId()).isInstanceOf(SecretId.absent().getClass()); @@ -65,7 +65,7 @@ class AppRoleClientAuthenticationProviderTests { properties.getAppRole().setRole("my-role"); AppRoleAuthenticationOptions options = AppRoleClientAuthenticationProvider - .getAppRoleAuthenticationOptions(properties); + .getAppRoleAuthenticationOptions(properties); assertThat(options.getAppRole()).isEqualTo("my-role"); assertThat(options.getRoleId()).isInstanceOf(RoleId.provided("foo").getClass()); @@ -80,7 +80,7 @@ class AppRoleClientAuthenticationProviderTests { properties.getAppRole().setRole("my-role"); AppRoleAuthenticationOptions options = AppRoleClientAuthenticationProvider - .getAppRoleAuthenticationOptions(properties); + .getAppRoleAuthenticationOptions(properties); assertThat(options.getAppRole()).isEqualTo("my-role"); assertThat(options.getRoleId()).isInstanceOf(RoleId.pull(VaultToken.of("token")).getClass()); @@ -94,7 +94,7 @@ class AppRoleClientAuthenticationProviderTests { properties.setToken("token"); AppRoleAuthenticationOptions options = AppRoleClientAuthenticationProvider - .getAppRoleAuthenticationOptions(properties); + .getAppRoleAuthenticationOptions(properties); assertThat(options.getRoleId()).isInstanceOf(RoleId.wrapped(VaultToken.of("token")).getClass()); assertThat(options.getSecretId()).isInstanceOf(SecretId.wrapped(VaultToken.of("token")).getClass()); @@ -108,7 +108,7 @@ class AppRoleClientAuthenticationProviderTests { properties.getAppRole().setSecretId("bar"); AppRoleAuthenticationOptions options = AppRoleClientAuthenticationProvider - .getAppRoleAuthenticationOptions(properties); + .getAppRoleAuthenticationOptions(properties); assertThat(options.getRoleId()).isInstanceOf(RoleId.wrapped(VaultToken.of("token")).getClass()); assertThat(options.getSecretId()).isInstanceOf(SecretId.provided("bar").getClass()); @@ -122,7 +122,7 @@ class AppRoleClientAuthenticationProviderTests { properties.getAppRole().setRoleId("foo"); AppRoleAuthenticationOptions options = AppRoleClientAuthenticationProvider - .getAppRoleAuthenticationOptions(properties); + .getAppRoleAuthenticationOptions(properties); assertThat(options.getRoleId()).isInstanceOf(RoleId.provided("foo").getClass()); assertThat(options.getSecretId()).isInstanceOf(SecretId.wrapped(VaultToken.of("token")).getClass()); @@ -134,7 +134,7 @@ class AppRoleClientAuthenticationProviderTests { VaultEnvironmentProperties properties = new VaultEnvironmentProperties(); assertThatThrownBy(() -> AppRoleClientAuthenticationProvider.getAppRoleAuthenticationOptions(properties)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -144,7 +144,7 @@ class AppRoleClientAuthenticationProviderTests { properties.getAppRole().setRole("my-role"); assertThatThrownBy(() -> AppRoleClientAuthenticationProvider.getAppRoleAuthenticationOptions(properties)) - .isInstanceOf(IllegalArgumentException.class); + .isInstanceOf(IllegalArgumentException.class); } } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/GenericResourceRepositoryTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/GenericResourceRepositoryTests.java index 68dc0003..29811159 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/GenericResourceRepositoryTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/GenericResourceRepositoryTests.java @@ -70,7 +70,7 @@ public class GenericResourceRepositoryTests { @BeforeEach public void init() { this.context = new SpringApplicationBuilder(NativeEnvironmentRepositoryTests.class).web(WebApplicationType.NONE) - .run(); + .run(); this.nativeRepository = new NativeEnvironmentRepository(this.context.getEnvironment(), new NativeEnvironmentProperties(), ObservationRegistry.NOOP); this.repository = new GenericResourceRepository(this.nativeRepository); @@ -97,9 +97,9 @@ public class GenericResourceRepositoryTests { @Test public void locateMissingResource() { Assertions - .assertThatThrownBy( - () -> assertThat(this.repository.findOne("blah", "default", "master", "foo.txt")).isNotNull()) - .isInstanceOf(NoSuchResourceException.class); + .assertThatThrownBy( + () -> assertThat(this.repository.findOne("blah", "default", "master", "foo.txt")).isNotNull()) + .isInstanceOf(NoSuchResourceException.class); } @Test @@ -109,7 +109,7 @@ public class GenericResourceRepositoryTests { this.repository.findOne("blah", "local", "master", "..%2F..%2Fdata-jdbc.sql"); }).isInstanceOf(NoSuchResourceException.class); Assertions.assertThat(capturedOutput.getAll()) - .contains("Path contains \"../\" after call to StringUtils#cleanPath"); + .contains("Path contains \"../\" after call to StringUtils#cleanPath"); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerIntegrationTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerIntegrationTests.java index e9056f47..b0ff74d3 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerIntegrationTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerIntegrationTests.java @@ -86,9 +86,9 @@ public class ResourceControllerIntegrationTests { public void environmentNoLabel() throws Exception { when(this.repository.findOne("foo", "default", "master", false)).thenReturn(new Environment("foo", "default")); when(this.resources.findOne("foo", "default", "master", "foo.txt")) - .thenReturn(new ClassPathResource("resource-controller/foo.txt")); + .thenReturn(new ClassPathResource("resource-controller/foo.txt")); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/master/foo.txt")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", "default", "master", false); verify(this.resources).findOne("foo", "default", "master", "foo.txt"); } @@ -96,11 +96,11 @@ public class ResourceControllerIntegrationTests { @Test public void resource() throws Exception { when(this.repository.findOne("foo", "default", "master", false)) - .thenReturn(new Environment("foo", "default", "master")); + .thenReturn(new Environment("foo", "default", "master")); when(this.resources.findOne("foo", "default", "master", "foo.txt")) - .thenReturn(new ClassPathResource("resource-controller/foo.txt")); + .thenReturn(new ClassPathResource("resource-controller/foo.txt")); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/master/foo.txt")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", "default", "master", false); verify(this.resources).findOne("foo", "default", "master", "foo.txt"); } @@ -108,12 +108,12 @@ public class ResourceControllerIntegrationTests { @Test public void resourceHttp() throws Exception { when(this.repository.findOne("foo", "default", "master", false)) - .thenReturn(new Environment("foo", "default", "master")); + .thenReturn(new Environment("foo", "default", "master")); when(this.resources.findOne("foo", "default", "master", "foo.txt")) - .thenReturn(new ClassPathResource("resource-controller/foo.txt")); + .thenReturn(new ClassPathResource("resource-controller/foo.txt")); ResponseEntity response = new TestRestTemplate() - .getForEntity("http://localhost:" + port + "/foo/default/master/foo.txt", String.class); + .getForEntity("http://localhost:" + port + "/foo/default/master/foo.txt", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); verify(this.repository).findOne("foo", "default", "master", false); verify(this.resources).findOne("foo", "default", "master", "foo.txt"); @@ -122,10 +122,10 @@ public class ResourceControllerIntegrationTests { @Test public void resourceHttpDoesNotExist() throws Exception { when(this.resources.findOne("foo", "default", "master", "doesNotExist.txt")) - .thenThrow(new NoSuchResourceException("Does not exist")); + .thenThrow(new NoSuchResourceException("Does not exist")); ResponseEntity response = new TestRestTemplate() - .getForEntity("http://localhost:" + port + "/foo/default/master/doesNotExist.txt", String.class); + .getForEntity("http://localhost:" + port + "/foo/default/master/doesNotExist.txt", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); verify(this.resources).findOne("foo", "default", "master", "doesNotExist.txt"); } @@ -133,11 +133,11 @@ public class ResourceControllerIntegrationTests { @Test public void resourceNoLabel() throws Exception { when(this.repository.findOne("foo", "default", null, false)) - .thenReturn(new Environment("foo", "default", "master")); + .thenReturn(new Environment("foo", "default", "master")); when(this.resources.findOne("foo", "default", null, "foo.txt")) - .thenReturn(new ClassPathResource("resource-controller/foo.txt")); + .thenReturn(new ClassPathResource("resource-controller/foo.txt")); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/foo.txt").param("useDefaultLabel", "")) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", "default", null, false); verify(this.resources).findOne("foo", "default", null, "foo.txt"); } @@ -145,12 +145,12 @@ public class ResourceControllerIntegrationTests { @Test public void resourceNoLabelHttp() throws Exception { when(this.repository.findOne("foo", "default", null, false)) - .thenReturn(new Environment("foo", "default", "master")); + .thenReturn(new Environment("foo", "default", "master")); when(this.resources.findOne("foo", "default", null, "foo.txt")) - .thenReturn(new ClassPathResource("resource-controller/foo.txt")); + .thenReturn(new ClassPathResource("resource-controller/foo.txt")); ResponseEntity response = new TestRestTemplate() - .getForEntity("http://localhost:" + port + "/foo/default/foo.txt?useDefaultLabel", String.class); + .getForEntity("http://localhost:" + port + "/foo/default/foo.txt?useDefaultLabel", String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); verify(this.repository).findOne("foo", "default", null, false); verify(this.resources).findOne("foo", "default", null, "foo.txt"); @@ -160,10 +160,12 @@ public class ResourceControllerIntegrationTests { public void binaryResourceNoLabel() throws Exception { when(this.repository.findOne("foo", "default", null)).thenReturn(new Environment("foo", "default", "master")); when(this.resources.findOne("foo", "default", null, "foo.txt")) - .thenReturn(new ClassPathResource("resource-controller/foo.txt")); - this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/foo.txt").param("useDefaultLabel", "") + .thenReturn(new ClassPathResource("resource-controller/foo.txt")); + this.mvc + .perform(MockMvcRequestBuilders.get("/foo/default/foo.txt") + .param("useDefaultLabel", "") .header(HttpHeaders.ACCEPT, MimeTypeUtils.APPLICATION_OCTET_STREAM_VALUE)) - .andExpect(MockMvcResultMatchers.status().isOk()); + .andExpect(MockMvcResultMatchers.status().isOk()); verify(this.repository).findOne("foo", "default", null); verify(this.resources).findOne("foo", "default", null, "foo.txt"); } @@ -171,9 +173,9 @@ public class ResourceControllerIntegrationTests { @Test public void resourceWithMissingLabel() throws Exception { when(this.resources.findOne("foo", "default", "missing", "foo.txt")) - .thenThrow(new NoSuchLabelException("Planned")); + .thenThrow(new NoSuchLabelException("Planned")); this.mvc.perform(MockMvcRequestBuilders.get("/foo/default/missing/foo.txt")) - .andExpect(MockMvcResultMatchers.status().isNotFound()); + .andExpect(MockMvcResultMatchers.status().isNotFound()); } @SpringBootConfiguration diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerTests.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerTests.java index 7ee6793e..079af5f7 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerTests.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/resource/ResourceControllerTests.java @@ -69,7 +69,7 @@ public class ResourceControllerTests { @BeforeEach public void init() { this.context = new SpringApplicationBuilder(NativeEnvironmentRepositoryTests.class).web(WebApplicationType.NONE) - .run(); + .run(); this.environmentRepository = new NativeEnvironmentRepository(this.context.getEnvironment(), new NativeEnvironmentProperties(), ObservationRegistry.NOOP); this.repository = new GenericResourceRepository(this.environmentRepository); @@ -85,7 +85,7 @@ public class ResourceControllerTests { this.environmentRepository.setSearchLocations("classpath:/test"); String resource = this.controller.retrieve("foo", "bar", "dev", "template.json", true); assertThat(replaceNewLines(resource)).matches("\\{\\s*\"foo\": \"dev_bar\"\\s*\\}") - .as("Wrong content: " + resource); + .as("Wrong content: " + resource); } @Test @@ -93,7 +93,7 @@ public class ResourceControllerTests { this.environmentRepository.setSearchLocations("classpath:/test"); String resource = this.controller.retrieve("foo", "bar", "dev", "template.json", false); assertThat(replaceNewLines(resource)).matches("\\{\\s*\"foo\": \"\\$\\{foo\\}\"\\s*\\}") - .as("Wrong content: " + resource); + .as("Wrong content: " + resource); } @Test @@ -101,7 +101,7 @@ public class ResourceControllerTests { this.environmentRepository.setSearchLocations("classpath:/test"); String resource = new String(this.controller.binary("foo", "bar", "dev", "template.json")); assertThat(replaceNewLines(resource)).matches("\\{\\s*\"foo\": \"\\$\\{foo\\}\"\\s*\\}") - .as("Wrong content: " + resource); + .as("Wrong content: " + resource); } @Test diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/FileBasedSshSessionFactoryTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/FileBasedSshSessionFactoryTest.java index acd8ea95..361de3f5 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/FileBasedSshSessionFactoryTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/FileBasedSshSessionFactoryTest.java @@ -94,8 +94,8 @@ public class FileBasedSshSessionFactoryTest { } private SshConfigStore.HostConfig getSshHostConfig(String hostName) { - return factory.createSshConfigStore(new File("dummy"), new File("dummy"), "localUserName").lookup(hostName, 22, - "userName"); + return factory.createSshConfigStore(new File("dummy"), new File("dummy"), "localUserName") + .lookup(hostName, 22, "userName"); } private void setupSessionFactory(JGitEnvironmentProperties sshKey) { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactoryTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactoryTest.java index 97742017..c9f467e4 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactoryTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/PropertyBasedSshSessionFactoryTest.java @@ -372,7 +372,8 @@ public class PropertyBasedSshSessionFactoryTest { List kayPairs; try { Spliterator spliterator = ((KeyIdentityProvider) factory.getDefaultKeys(new File("."))) - .loadKeys(session).spliterator(); + .loadKeys(session) + .spliterator(); kayPairs = StreamSupport.stream(spliterator, false).collect(Collectors.toList()); } @@ -385,26 +386,26 @@ public class PropertyBasedSshSessionFactoryTest { private PublicKey getSshHostKey(String hostname) { InetSocketAddress address = setupSocketAddress(hostname); - List publicKeys = factory.getServerKeyDatabase(null, null).lookup("address", address, - mock(ServerKeyDatabase.Configuration.class)); + List publicKeys = factory.getServerKeyDatabase(null, null) + .lookup("address", address, mock(ServerKeyDatabase.Configuration.class)); return publicKeys.isEmpty() ? null : publicKeys.get(0); } private boolean isKnownKeyForHost(PublicKey publicKey, String hostname) { InetSocketAddress address = setupSocketAddress(hostname); - return factory.getServerKeyDatabase(null, null).accept("address", address, publicKey, - mock(ServerKeyDatabase.Configuration.class), null); + return factory.getServerKeyDatabase(null, null) + .accept("address", address, publicKey, mock(ServerKeyDatabase.Configuration.class), null); } private SshConfigStore.HostConfig getSshHostConfig(String hostname) { - return factory.createSshConfigStore(new File("dummy"), new File("dummy"), "localUserName").lookup(hostname, 22, - "userName"); + return factory.createSshConfigStore(new File("dummy"), new File("dummy"), "localUserName") + .lookup(hostname, 22, "userName"); } private SshConfigStore.HostConfig getDefaultSshHostConfig(String hostName, int port, String username) { return factory.createSshConfigStore(new File("dummy"), new File("dummy"), "localUserName") - .lookupDefault(hostName, port, username); + .lookupDefault(hostName, port, username); } private void setupSessionFactory(JGitEnvironmentProperties sshKey) { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshPropertyValidatorTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshPropertyValidatorTest.java index 79d8e35b..b0e976bc 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshPropertyValidatorTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/ssh/SshPropertyValidatorTest.java @@ -90,7 +90,7 @@ public class SshPropertyValidatorTest { validSettings.setHostKeyAlgorithm("ssh-rsa"); Set> constraintViolations = validator - .validate(validSettings); + .validate(validSettings); assertThat(constraintViolations).hasSize(0); } @@ -102,7 +102,7 @@ public class SshPropertyValidatorTest { invalidKey.setPrivateKey("-----BEGIN OPENSSH PRIVATE KEY-----\nFOOBAR"); Set> constraintViolations = validator - .validate(invalidKey); + .validate(invalidKey); assertThat(constraintViolations).hasSize(1); } @@ -114,7 +114,7 @@ public class SshPropertyValidatorTest { invalidKey.setPrivateKey("invalid_key"); Set> constraintViolations = validator - .validate(invalidKey); + .validate(invalidKey); assertThat(constraintViolations).hasSize(1); } @@ -125,7 +125,7 @@ public class SshPropertyValidatorTest { missingKey.setIgnoreLocalSshSettings(true); Set> constraintViolations = validator - .validate(missingKey); + .validate(missingKey); assertThat(constraintViolations).hasSize(1); } @@ -138,7 +138,7 @@ public class SshPropertyValidatorTest { missingAlgo.setHostKey("some_host"); Set> constraintViolations = validator - .validate(missingAlgo); + .validate(missingAlgo); assertThat(constraintViolations).hasSize(1); } @@ -151,7 +151,7 @@ public class SshPropertyValidatorTest { missingHostKey.setHostKeyAlgorithm("ssh-rsa"); Set> constraintViolations = validator - .validate(missingHostKey); + .validate(missingHostKey); assertThat(constraintViolations).hasSize(1); } @@ -165,7 +165,7 @@ public class SshPropertyValidatorTest { unsupportedAlgo.setHostKeyAlgorithm("unsupported"); Set> constraintViolations = validator - .validate(unsupportedAlgo); + .validate(unsupportedAlgo); assertThat(constraintViolations).hasSize(1); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProviderTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProviderTest.java index 479efd94..2eaa17d3 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProviderTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/GitSkipSslValidationCredentialsProviderTest.java @@ -54,15 +54,18 @@ public class GitSkipSslValidationCredentialsProviderTest { @Test public void testCanHandle() { assertThat(GitSkipSslValidationCredentialsProvider.canHandle("https://github.com/org/repo")) - .as("GitSkipSslValidationCredentialsProvider only handles HTTPS uris").isTrue(); + .as("GitSkipSslValidationCredentialsProvider only handles HTTPS uris") + .isTrue(); assertThat(GitSkipSslValidationCredentialsProvider.canHandle("git@github.com:org/repo")) - .as("GitSkipSslValidationCredentialsProvider only handles HTTPS uris").isFalse(); + .as("GitSkipSslValidationCredentialsProvider only handles HTTPS uris") + .isFalse(); } @Test public void testIsInteractive() { assertThat(this.skipSslValidationCredentialsProvider.isInteractive()) - .as("GitSkipSslValidationCredentialsProvider with no delegate requires no user interaction").isFalse(); + .as("GitSkipSslValidationCredentialsProvider with no delegate requires no user interaction") + .isFalse(); } @Test @@ -73,7 +76,8 @@ public class GitSkipSslValidationCredentialsProviderTest { when(this.mockDelegateCredentialsProvider.isInteractive()).thenReturn(true); assertThat(this.skipSslValidationCredentialsProvider.isInteractive()) - .as("With a delegate provider, isInteractive value depends on the delegate").isTrue(); + .as("With a delegate provider, isInteractive value depends on the delegate") + .isTrue(); } @Test @@ -81,13 +85,13 @@ public class GitSkipSslValidationCredentialsProviderTest { CredentialItem informationalMessage = new CredentialItem.InformationalMessage( "text " + JGitText.get().sslFailureTrustExplanation + " more text"); assertThat(this.skipSslValidationCredentialsProvider.supports(informationalMessage)) - .as("GitSkipSslValidationCredentialsProvider should always support SSL failure InformationalMessage") - .isTrue(); + .as("GitSkipSslValidationCredentialsProvider should always support SSL failure InformationalMessage") + .isTrue(); informationalMessage = new CredentialItem.InformationalMessage("unrelated"); assertThat(this.skipSslValidationCredentialsProvider.supports(informationalMessage)) - .as("GitSkipSslValidationCredentialsProvider should not support unrelated InformationalMessage items") - .isFalse(); + .as("GitSkipSslValidationCredentialsProvider should not support unrelated InformationalMessage items") + .isFalse(); } @Test @@ -102,22 +106,23 @@ public class GitSkipSslValidationCredentialsProviderTest { public void testSupportsSslValidationYesNoTypes() { CredentialItem yesNoType = new CredentialItem.YesNoType(JGitText.get().sslTrustNow); assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)) - .as("GitSkipSslValidationCredentialsProvider should always support the trust now YesNoType item") - .isTrue(); + .as("GitSkipSslValidationCredentialsProvider should always support the trust now YesNoType item") + .isTrue(); yesNoType = new CredentialItem.YesNoType(MessageFormat.format(JGitText.get().sslTrustForRepo, "/a/path.git")); assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)) - .as("GitSkipSslValidationCredentialsProvider should always support the trust repo YesNoType item") - .isTrue(); + .as("GitSkipSslValidationCredentialsProvider should always support the trust repo YesNoType item") + .isTrue(); yesNoType = new CredentialItem.YesNoType(JGitText.get().sslTrustAlways); assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)) - .as("GitSkipSslValidationCredentialsProvider should always support the trust always YesNoType item") - .isTrue(); + .as("GitSkipSslValidationCredentialsProvider should always support the trust always YesNoType item") + .isTrue(); yesNoType = new CredentialItem.YesNoType("unrelated"); assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)) - .as("GitSkipSslValidationCredentialsProvider should not support unrelated YesNoType items").isFalse(); + .as("GitSkipSslValidationCredentialsProvider should not support unrelated YesNoType items") + .isFalse(); } @Test @@ -135,7 +140,8 @@ public class GitSkipSslValidationCredentialsProviderTest { boolean supportsItems = this.skipSslValidationCredentialsProvider.supports(usernameCredentialItem); assertThat(supportsItems) - .as("Credential item types not related to SSL validation skipping should not be supported").isFalse(); + .as("Credential item types not related to SSL validation skipping should not be supported") + .isFalse(); } @Test @@ -148,9 +154,9 @@ public class GitSkipSslValidationCredentialsProviderTest { boolean supportsItems = this.skipSslValidationCredentialsProvider.supports(usernameCredentialItem); - assertThat(supportsItems).as( - "GitSkipSslValidationCredentialsProvider must support the types supported by its delegate CredentialsProvider") - .isTrue(); + assertThat(supportsItems) + .as("GitSkipSslValidationCredentialsProvider must support the types supported by its delegate CredentialsProvider") + .isTrue(); } @Test @@ -173,13 +179,15 @@ public class GitSkipSslValidationCredentialsProviderTest { CredentialItem passwordCredentialItem = new CredentialItem.Password(); when(this.mockDelegateCredentialsProvider.get(uri, usernameCredentialItem, passwordCredentialItem)) - .thenReturn(true); + .thenReturn(true); boolean getSuccessful = this.skipSslValidationCredentialsProvider.get(uri, usernameCredentialItem, passwordCredentialItem); - assertThat(getSuccessful).as("GitSkipSslValidationCredentialsProvider " - + "must successfully get the types supported by its delegate CredentialsProvider").isTrue(); + assertThat(getSuccessful) + .as("GitSkipSslValidationCredentialsProvider " + + "must successfully get the types supported by its delegate CredentialsProvider") + .isTrue(); } @Test @@ -191,11 +199,12 @@ public class GitSkipSslValidationCredentialsProviderTest { boolean getSuccessful = this.skipSslValidationCredentialsProvider.get(uri, message, trustNow, trustAlways); - assertThat(getSuccessful).as( - "SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping") - .isTrue(); + assertThat(getSuccessful) + .as("SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping") + .isTrue(); assertThat(trustNow.getValue()) - .as("SkipSSlValidationCredentialsProvider should trust the current repo operation").isTrue(); + .as("SkipSSlValidationCredentialsProvider should trust the current repo operation") + .isTrue(); assertThat(trustAlways.getValue()).as("We should not globally skip all SSL validation").isFalse(); } @@ -218,11 +227,12 @@ public class GitSkipSslValidationCredentialsProviderTest { boolean getSuccessful = this.skipSslValidationCredentialsProvider.get(uri, message, trustNow, trustForRepo, trustAlways); - assertThat(getSuccessful).as( - "SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping") - .isTrue(); + assertThat(getSuccessful) + .as("SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping") + .isTrue(); assertThat(trustNow.getValue()) - .as("SkipSSlValidationCredentialsProvider should trust the current repo operation").isTrue(); + .as("SkipSSlValidationCredentialsProvider should trust the current repo operation") + .isTrue(); assertThat(trustForRepo.getValue()).as("Future operations on this repository should also be trusted").isTrue(); assertThat(trustAlways.getValue()).as("We should not globally skip all SSL validation").isFalse(); } diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClient4SupportTest.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClient4SupportTest.java index 6f0e6b06..73a394ac 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClient4SupportTest.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/support/HttpClient4SupportTest.java @@ -91,7 +91,7 @@ public class HttpClient4SupportTest { try { httpClient = HttpClient4Support.builder(properties).build(); response = httpClient - .execute(new HttpGet("https://localhost:" + wireMockServer.httpsPort() + "/test/proxy")); + .execute(new HttpGet("https://localhost:" + wireMockServer.httpsPort() + "/test/proxy")); } finally { if (response != null) { diff --git a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/test/TestConfigServerApplication.java b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/test/TestConfigServerApplication.java index 5049ef47..e549cd1e 100644 --- a/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/test/TestConfigServerApplication.java +++ b/spring-cloud-config-server/src/test/java/org/springframework/cloud/config/server/test/TestConfigServerApplication.java @@ -26,7 +26,7 @@ public class TestConfigServerApplication { public static void main(String[] args) { new SpringApplicationBuilder(TestConfigServerApplication.class).properties("spring.config.name=configserver") - .run(args); + .run(args); } }