diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java index 6ccd313c..a164a4f2 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/FeaturesEndpoint.java @@ -18,6 +18,7 @@ package org.springframework.cloud.client.actuator; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -152,16 +153,16 @@ public class FeaturesEndpoint implements ApplicationContextAware { Feature feature = (Feature) o; - if (this.type != null ? !this.type.equals(feature.type) : feature.type != null) { + if (!Objects.equals(this.type, feature.type)) { return false; } - if (this.name != null ? !this.name.equals(feature.name) : feature.name != null) { + if (!Objects.equals(this.name, feature.name)) { return false; } - if (this.version != null ? !this.version.equals(feature.version) : feature.version != null) { + if (!Objects.equals(this.version, feature.version)) { return false; } - return this.vendor != null ? this.vendor.equals(feature.vendor) : feature.vendor == null; + return Objects.equals(this.vendor, feature.vendor); } @Override diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java index 2d7faedd..8534e91f 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/actuator/HasFeatures.java @@ -36,11 +36,11 @@ public class HasFeatures { } public static HasFeatures abstractFeatures(Class... abstractFeatures) { - return new HasFeatures(Arrays.asList(abstractFeatures), Collections.emptyList()); + return new HasFeatures(Arrays.asList(abstractFeatures), Collections.emptyList()); } public static HasFeatures namedFeatures(NamedFeature... namedFeatures) { - return new HasFeatures(Collections.>emptyList(), Arrays.asList(namedFeatures)); + return new HasFeatures(Collections.emptyList(), Arrays.asList(namedFeatures)); } public static HasFeatures namedFeature(String name, Class type) { diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/CircuitBreaker.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/CircuitBreaker.java index d8b144d6..080841d6 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/CircuitBreaker.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/CircuitBreaker.java @@ -30,7 +30,7 @@ public interface CircuitBreaker { return run(toRun, throwable -> { throw new NoFallbackAvailableException("No fallback available.", throwable); }); - }; + } T run(Supplier toRun, Function fallback); diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationDocumentation.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationDocumentation.java index be07c943..8b062619 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationDocumentation.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/circuitbreaker/observation/CircuitBreakerObservationDocumentation.java @@ -84,7 +84,7 @@ enum CircuitBreakerObservationDocumentation implements ObservationDocumentation public String asString() { return "spring.cloud.circuitbreaker.type"; } - }; + } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java index 4e65623b..a57ff0a8 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelector.java @@ -52,8 +52,7 @@ public class EnableDiscoveryClientImportSelector extends SpringFactoryImportSele } else { Environment env = getEnvironment(); - if (ConfigurableEnvironment.class.isInstance(env)) { - ConfigurableEnvironment configEnv = (ConfigurableEnvironment) env; + if (env instanceof ConfigurableEnvironment configEnv) { LinkedHashMap map = new LinkedHashMap<>(); map.put("spring.cloud.service-registry.auto-registration.enabled", false); MapPropertySource propertySource = new MapPropertySource("springCloudDiscoveryClient", map); diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java index 3e4f0d39..8f6b2f8d 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorProperties.java @@ -63,12 +63,8 @@ public class DiscoveryClientHealthIndicatorProperties { @Override public String toString() { - final StringBuffer sb = new StringBuffer("DiscoveryClientHealthIndicatorProperties{"); - sb.append("enabled=").append(this.enabled); - sb.append(", includeDescription=").append(this.includeDescription); - sb.append(", useServicesQuery=").append(this.useServicesQuery); - sb.append('}'); - return sb.toString(); + return "DiscoveryClientHealthIndicatorProperties{" + "enabled=" + this.enabled + ", includeDescription=" + + this.includeDescription + ", useServicesQuery=" + this.useServicesQuery + '}'; } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributor.java index 42727ba8..cde4574c 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributor.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributor.java @@ -57,7 +57,7 @@ public class DiscoveryCompositeHealthContributor implements CompositeHealthContr } private NamedContributor asNamedContributor(DiscoveryHealthIndicator indicator) { - return new NamedContributor() { + return new NamedContributor<>() { @Override public String getName() { diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/reactive/ReactiveDiscoveryCompositeHealthContributor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/reactive/ReactiveDiscoveryCompositeHealthContributor.java index 5c4bf745..dcaeac4a 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/reactive/ReactiveDiscoveryCompositeHealthContributor.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/discovery/health/reactive/ReactiveDiscoveryCompositeHealthContributor.java @@ -54,7 +54,7 @@ public class ReactiveDiscoveryCompositeHealthContributor implements CompositeRea } private NamedContributor asNamedContributor(ReactiveDiscoveryHealthIndicator indicator) { - return new NamedContributor() { + return new NamedContributor<>() { @Override public String getName() { diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java index e173c61b..f696ade8 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/hypermedia/RemoteResourceRefresher.java @@ -16,6 +16,7 @@ package org.springframework.cloud.client.hypermedia; +import java.time.Duration; import java.util.List; import org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar; @@ -52,13 +53,8 @@ public class RemoteResourceRefresher extends ContextLifecycleScheduledTaskRegist public void afterPropertiesSet() { for (final RemoteResource resource : this.discoveredResources) { - addFixedDelayTask(new IntervalTask(new Runnable() { - - @Override - public void run() { - resource.verifyOrDiscover(); - } - }, this.fixedDelay, this.initialDelay)); + addFixedDelayTask(new IntervalTask(resource::verifyOrDiscover, Duration.ofMillis(fixedDelay), + Duration.ofMillis(initialDelay))); } super.afterPropertiesSet(); diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java index ff142e2c..fd83c895 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeException.java @@ -43,7 +43,7 @@ public class ClientHttpResponseStatusCodeException extends RetryableStatusCodeEx */ public ClientHttpResponseStatusCodeException(String serviceId, ClientHttpResponse response, byte[] body) throws IOException { - super(serviceId, response.getRawStatusCode(), response, null); + super(serviceId, response.getStatusCode().value(), response, null); this.response = new ClientHttpResponseWrapper(response, body); } @@ -65,7 +65,7 @@ public class ClientHttpResponseStatusCodeException extends RetryableStatusCodeEx @Override public int getRawStatusCode() throws IOException { - return this.response.getRawStatusCode(); + return this.response.getStatusCode().value(); } @Override diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequest.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequest.java index 9cafa174..7079ad67 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequest.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequest.java @@ -59,10 +59,9 @@ public class DefaultRequest implements Request { if (this == o) { return true; } - if (!(o instanceof DefaultRequest)) { + if (!(o instanceof DefaultRequest that)) { return false; } - DefaultRequest that = (DefaultRequest) o; return Objects.equals(context, that.context); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequestContext.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequestContext.java index 3c18ea3d..f0bd9d21 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequestContext.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultRequestContext.java @@ -62,10 +62,9 @@ public class DefaultRequestContext extends HintRequestContext { if (this == o) { return true; } - if (!(o instanceof DefaultRequestContext)) { + if (!(o instanceof DefaultRequestContext that)) { return false; } - DefaultRequestContext that = (DefaultRequestContext) o; return Objects.equals(clientRequest, that.clientRequest); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultResponse.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultResponse.java index d2cf423e..7e966338 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultResponse.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/DefaultResponse.java @@ -55,10 +55,9 @@ public class DefaultResponse implements Response { if (this == o) { return true; } - if (!(o instanceof DefaultResponse)) { + if (!(o instanceof DefaultResponse that)) { return false; } - DefaultResponse that = (DefaultResponse) o; return Objects.equals(serviceInstance, that.serviceInstance); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/HintRequestContext.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/HintRequestContext.java index df02d9d0..e62a1c61 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/HintRequestContext.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/HintRequestContext.java @@ -72,10 +72,9 @@ public class HintRequestContext implements TimedRequestContext { if (this == o) { return true; } - if (!(o instanceof HintRequestContext)) { + if (!(o instanceof HintRequestContext that)) { return false; } - HintRequestContext that = (HintRequestContext) o; return Objects.equals(hint, that.hint); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java index 000a9440..ccbf59cb 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRecoveryCallback.java @@ -45,8 +45,7 @@ public abstract class LoadBalancedRecoveryCallback implements RecoveryCall public T recover(RetryContext context) throws Exception { Throwable lastThrowable = context.getLastThrowable(); if (lastThrowable != null) { - if (lastThrowable instanceof RetryableStatusCodeException) { - RetryableStatusCodeException ex = (RetryableStatusCodeException) lastThrowable; + if (lastThrowable instanceof RetryableStatusCodeException ex) { return createResponse((R) ex.getResponse(), ex.getUri()); } else if (lastThrowable instanceof Exception) { diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RequestData.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RequestData.java index 5589a3aa..bd666d2b 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RequestData.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RequestData.java @@ -141,10 +141,9 @@ public class RequestData { if (this == o) { return true; } - if (!(o instanceof RequestData)) { + if (!(o instanceof RequestData that)) { return false; } - RequestData that = (RequestData) o; return httpMethod == that.httpMethod && Objects.equals(url, that.url) && Objects.equals(headers, that.headers) && Objects.equals(cookies, that.cookies) && Objects.equals(attributes, that.attributes); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java index 2505df8f..a4949c0e 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptor.java @@ -90,8 +90,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto RetryTemplate template = createRetryTemplate(serviceName, request, retryPolicy); return template.execute(context -> { ServiceInstance serviceInstance = null; - if (context instanceof LoadBalancedRetryContext) { - LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context; + if (context instanceof LoadBalancedRetryContext lbContext) { serviceInstance = lbContext.getServiceInstance(); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Retrieved service instance from LoadBalancedRetryContext: %s", @@ -109,8 +108,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto + "Reattempting service instance selection"); } ServiceInstance previousServiceInstance = null; - if (context instanceof LoadBalancedRetryContext) { - LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context; + if (context instanceof LoadBalancedRetryContext lbContext) { previousServiceInstance = lbContext.getPreviousServiceInstance(); } DefaultRequest lbRequest = new DefaultRequest<>( @@ -120,8 +118,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto if (LOG.isDebugEnabled()) { LOG.debug(String.format("Selected service instance: %s", serviceInstance)); } - if (context instanceof LoadBalancedRetryContext) { - LoadBalancedRetryContext lbContext = (LoadBalancedRetryContext) context; + if (context instanceof LoadBalancedRetryContext lbContext) { lbContext.setServiceInstance(serviceInstance); } Response lbResponse = new DefaultResponse(serviceInstance); @@ -139,7 +136,7 @@ public class RetryLoadBalancerInterceptor implements ClientHttpRequestIntercepto new RetryableRequestContext(null, new RequestData(request), hint)); ServiceInstance finalServiceInstance = serviceInstance; ClientHttpResponse response = loadBalancer.execute(serviceName, finalServiceInstance, lbRequest); - int statusCode = response.getRawStatusCode(); + int statusCode = response.getStatusCode().value(); if (retryPolicy != null && retryPolicy.retryableStatusCode(statusCode)) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Retrying on status code: %d", statusCode)); diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableRequestContext.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableRequestContext.java index a2ad0c0c..a796b1d2 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableRequestContext.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/RetryableRequestContext.java @@ -66,13 +66,12 @@ public class RetryableRequestContext extends RequestDataContext { if (this == o) { return true; } - if (!(o instanceof RetryableRequestContext)) { + if (!(o instanceof RetryableRequestContext context)) { return false; } if (!super.equals(o)) { return false; } - RetryableRequestContext context = (RetryableRequestContext) o; return Objects.equals(previousServiceInstance, context.previousServiceInstance); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunction.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunction.java index 3f586130..4afeedae 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunction.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunction.java @@ -97,7 +97,7 @@ public class ReactorLoadBalancerExchangeFilterFunction implements LoadBalancedEx URI originalUrl = clientRequest.url(); String serviceId = originalUrl.getHost(); if (serviceId == null) { - String message = String.format("Request URI does not contain a valid hostname: %s", originalUrl.toString()); + String message = String.format("Request URI does not contain a valid hostname: %s", originalUrl); if (LOG.isWarnEnabled()) { LOG.warn(message); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunction.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunction.java index 2b195170..aab503c2 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunction.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunction.java @@ -106,7 +106,7 @@ public class RetryableLoadBalancerExchangeFilterFunction implements LoadBalanced URI originalUrl = clientRequest.url(); String serviceId = originalUrl.getHost(); if (serviceId == null) { - String message = String.format("Request URI does not contain a valid hostname: %s", originalUrl.toString()); + String message = String.format("Request URI does not contain a valid hostname: %s", originalUrl); if (LOG.isWarnEnabled()) { LOG.warn(message); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/ConfigDataMissingEnvironmentPostProcessor.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/ConfigDataMissingEnvironmentPostProcessor.java index a086e139..074d6587 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/ConfigDataMissingEnvironmentPostProcessor.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/ConfigDataMissingEnvironmentPostProcessor.java @@ -103,7 +103,7 @@ public abstract class ConfigDataMissingEnvironmentPostProcessor implements Envir } private boolean propertySourceWithConfigImport(PropertySource propertySource) { - if (CompositePropertySource.class.isInstance(propertySource)) { + if (propertySource instanceof CompositePropertySource) { return ((CompositePropertySource) propertySource).getPropertySources().stream() .anyMatch(this::propertySourceWithConfigImport); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/config/CommonsConfigAutoConfiguration.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/config/CommonsConfigAutoConfiguration.java index 95647158..c2cc85dc 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/config/CommonsConfigAutoConfiguration.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/config/CommonsConfigAutoConfiguration.java @@ -37,8 +37,7 @@ public class CommonsConfigAutoConfiguration { @Nullable DefaultsBindHandlerAdvisor.MappingsProvider[] providers) { Map additionalMappings = new HashMap<>(); if (!ObjectUtils.isEmpty(providers)) { - for (int i = 0; i < providers.length; i++) { - DefaultsBindHandlerAdvisor.MappingsProvider mappingsProvider = providers[i]; + for (DefaultsBindHandlerAdvisor.MappingsProvider mappingsProvider : providers) { additionalMappings.putAll(mappingsProvider.getDefaultMappings()); } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactory.java index b90beefb..ed57c3c1 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientConnectionManagerFactory.java @@ -19,7 +19,6 @@ package org.springframework.cloud.commons.httpclient; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; -import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; @@ -68,10 +67,7 @@ public class DefaultApacheHttpClientConnectionManagerFactory implements ApacheHt registryBuilder.register(HTTPS_SCHEME, new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)); } - catch (NoSuchAlgorithmException e) { - LOG.warn("Error creating SSLContext", e); - } - catch (KeyManagementException e) { + catch (NoSuchAlgorithmException | KeyManagementException e) { LOG.warn("Error creating SSLContext", e); } } @@ -88,14 +84,14 @@ public class DefaultApacheHttpClientConnectionManagerFactory implements ApacheHt return connectionManager; } - class DisabledValidationTrustManager implements X509TrustManager { + static class DisabledValidationTrustManager implements X509TrustManager { @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) { } @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) { } @Override diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactory.java index 22da0053..74246acb 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/DefaultOkHttpClientFactory.java @@ -56,10 +56,7 @@ public class DefaultOkHttpClientFactory implements OkHttpClientFactory { this.builder.sslSocketFactory(disabledSSLSocketFactory, disabledTrustManager); this.builder.hostnameVerifier(new TrustAllHostnames()); } - catch (NoSuchAlgorithmException e) { - LOG.warn("Error setting SSLSocketFactory in OKHttpClient", e); - } - catch (KeyManagementException e) { + catch (NoSuchAlgorithmException | KeyManagementException e) { LOG.warn("Error setting SSLSocketFactory in OKHttpClient", e); } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientFactory.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientFactory.java index 94b2586e..cba0c79f 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientFactory.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/httpclient/OkHttpClientFactory.java @@ -16,7 +16,6 @@ package org.springframework.cloud.commons.httpclient; -import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; @@ -45,11 +44,11 @@ public interface OkHttpClientFactory { class DisableValidationTrustManager implements X509TrustManager { @Override - public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + public void checkClientTrusted(X509Certificate[] x509Certificates, String s) { } @Override - public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { + public void checkServerTrusted(X509Certificate[] x509Certificates, String s) { } @Override diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/TaskSchedulerWrapper.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/TaskSchedulerWrapper.java index ab2dbcb7..20685db6 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/TaskSchedulerWrapper.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/commons/util/TaskSchedulerWrapper.java @@ -43,14 +43,14 @@ public class TaskSchedulerWrapper implements Initializi @Override public void destroy() throws Exception { - if (DisposableBean.class.isInstance(taskScheduler)) { + if (taskScheduler instanceof DisposableBean) { ((DisposableBean) this.taskScheduler).destroy(); } } @Override public void afterPropertiesSet() throws Exception { - if (InitializingBean.class.isInstance(taskScheduler)) { + if (taskScheduler instanceof InitializingBean) { ((InitializingBean) this.taskScheduler).afterPropertiesSet(); } } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierProperties.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierProperties.java index e73d3729..eab99cae 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierProperties.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/CompatibilityVerifierProperties.java @@ -16,7 +16,6 @@ package org.springframework.cloud.configuration; -import java.util.Arrays; import java.util.List; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -37,7 +36,7 @@ public class CompatibilityVerifierProperties { * the patch version if you don't want to specify a concrete value. Example: * {@code 3.4.x} */ - private List compatibleBootVersions = Arrays.asList("3.0.x"); + private List compatibleBootVersions = List.of("3.0.x"); public boolean isEnabled() { return this.enabled; diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java index 10831005..0f463c91 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/SpringBootVersionVerifier.java @@ -33,7 +33,7 @@ class SpringBootVersionVerifier implements CompatibilityVerifier { private static final Log log = LogFactory.getLog(SpringBootVersionVerifier.class); - final Map ACCEPTED_VERSIONS = new HashMap() { + final Map ACCEPTED_VERSIONS = new HashMap<>() { { this.put("3.0", is3_0()); } @@ -105,11 +105,12 @@ class SpringBootVersionVerifier implements CompatibilityVerifier { } private String action() { - return String.format("Change Spring Boot version to one of the following versions %s .\n" - + "You can find the latest Spring Boot versions here [%s]. \n" - + "If you want to learn more about the Spring Cloud Release train compatibility, you " - + "can visit this page [%s] and check the [Release Trains] section.\n" - + "If you want to disable this check, just set the property [spring.cloud.compatibility-verifier.enabled=false]", + return String.format( + """ + Change Spring Boot version to one of the following versions %s . + You can find the latest Spring Boot versions here [%s].\s + If you want to learn more about the Spring Cloud Release train compatibility, you can visit this page [%s] and check the [Release Trains] section. + If you want to disable this check, just set the property [spring.cloud.compatibility-verifier.enabled=false]""", this.acceptedVersions, "https://spring.io/projects/spring-boot#learn", "https://spring.io/projects/spring-cloud#overview"); } diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/TlsProperties.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/TlsProperties.java index 6b8befa6..0eca22c4 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/TlsProperties.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/TlsProperties.java @@ -16,8 +16,6 @@ package org.springframework.cloud.configuration; -import java.util.Collections; -import java.util.HashMap; import java.util.Map; import org.springframework.core.io.Resource; @@ -48,13 +46,8 @@ public class TlsProperties { private String trustStorePassword = ""; private static Map extTypes() { - Map result = new HashMap<>(); - result.put("p12", "PKCS12"); - result.put("pfx", "PKCS12"); - result.put("jks", "JKS"); - - return Collections.unmodifiableMap(result); + return Map.of("p12", "PKCS12", "pfx", "PKCS12", "jks", "JKS"); } public boolean isEnabled() { diff --git a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/VerificationResult.java b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/VerificationResult.java index 7063ec44..55aa64fc 100644 --- a/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/VerificationResult.java +++ b/spring-cloud-commons/src/main/java/org/springframework/cloud/configuration/VerificationResult.java @@ -60,10 +60,9 @@ final class VerificationResult { if (this == o) { return true; } - if (!(o instanceof VerificationResult)) { + if (!(o instanceof VerificationResult that)) { return false; } - VerificationResult that = (VerificationResult) o; return description.equals(that.description) && action.equals(that.action); } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelectorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelectorTests.java index 23fbf573..2c398c86 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelectorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/EnableDiscoveryClientImportSelectorTests.java @@ -45,7 +45,7 @@ public class EnableDiscoveryClientImportSelectorTests { @BeforeEach public void setup() { - MockitoAnnotations.initMocks(this); + MockitoAnnotations.openMocks(this); this.importSelector.setBeanClassLoader(getClass().getClassLoader()); this.importSelector.setEnvironment(this.environment); } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorTests.java index 5836107e..eefea584 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryClientHealthIndicatorTests.java @@ -16,7 +16,7 @@ package org.springframework.cloud.client.discovery.health; -import java.util.Arrays; +import java.util.List; import org.junit.jupiter.api.Test; @@ -87,7 +87,7 @@ public class DiscoveryClientHealthIndicatorTests { public DiscoveryClient discoveryClient() { DiscoveryClient mock = mock(DiscoveryClient.class); given(mock.description()).willReturn("TestDiscoveryClient"); - given(mock.getServices()).willReturn(Arrays.asList("TestService1")); + given(mock.getServices()).willReturn(List.of("TestService1")); return mock; } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributorTests.java index 325c1b85..258f7bd4 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/discovery/health/DiscoveryCompositeHealthContributorTests.java @@ -38,31 +38,29 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException public class DiscoveryCompositeHealthContributorTests { @Test - public void createWhenIndicatorsAreNullThrowsException() throws Exception { + public void createWhenIndicatorsAreNullThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new DiscoveryCompositeHealthContributor(null)) .withMessage("'indicators' must not be null"); } @Test - public void getContributorReturnsContributor() throws Exception { + public void getContributorReturnsContributor() { TestDiscoveryHealthIndicator indicator = new TestDiscoveryHealthIndicator("test", Health.up().build()); - DiscoveryCompositeHealthContributor composite = new DiscoveryCompositeHealthContributor( - Arrays.asList(indicator)); + DiscoveryCompositeHealthContributor composite = new DiscoveryCompositeHealthContributor(List.of(indicator)); HealthIndicator adapted = (HealthIndicator) composite.getContributor("test"); assertThat(adapted).isNotNull(); assertThat(adapted.health()).isSameAs(indicator.health()); } @Test - public void getContributorWhenMissingReturnsNull() throws Exception { + public void getContributorWhenMissingReturnsNull() { TestDiscoveryHealthIndicator indicator = new TestDiscoveryHealthIndicator("test", Health.up().build()); - DiscoveryCompositeHealthContributor composite = new DiscoveryCompositeHealthContributor( - Arrays.asList(indicator)); + DiscoveryCompositeHealthContributor composite = new DiscoveryCompositeHealthContributor(List.of(indicator)); assertThat((HealthIndicator) composite.getContributor("missing")).isNull(); } @Test - public void iteratorIteratesNamedContributors() throws Exception { + public void iteratorIteratesNamedContributors() { TestDiscoveryHealthIndicator indicator1 = new TestDiscoveryHealthIndicator("test1", Health.up().build()); TestDiscoveryHealthIndicator indicator2 = new TestDiscoveryHealthIndicator("test2", Health.down().build()); DiscoveryCompositeHealthContributor composite = new DiscoveryCompositeHealthContributor( diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeExceptionTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeExceptionTest.java index 19607e80..a51f3330 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeExceptionTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/ClientHttpResponseStatusCodeExceptionTest.java @@ -44,23 +44,23 @@ public class ClientHttpResponseStatusCodeExceptionTest { ClientHttpResponseStatusCodeException exp = new ClientHttpResponseStatusCodeException("service", response, response.getStatusText().getBytes()); ClientHttpResponse expResponse = exp.getResponse(); - then(expResponse.getRawStatusCode()).isEqualTo(response.getRawStatusCode()); + then(expResponse.getStatusCode().value()).isEqualTo(response.getRawStatusCode()); then(expResponse.getStatusText()).isEqualTo(response.getStatusText()); then(expResponse.getHeaders()).isEqualTo(response.getHeaders()); then(new String(StreamUtils.copyToByteArray(expResponse.getBody()))).isEqualTo(response.getStatusText()); } - class MyClientHttpResponse extends AbstractClientHttpResponse { + static class MyClientHttpResponse extends AbstractClientHttpResponse { private boolean closed = false; @Override - public int getRawStatusCode() throws IOException { + public int getRawStatusCode() { return 200; } @Override - public String getStatusText() throws IOException { + public String getStatusText() { return "foo"; } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContextTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContextTest.java index d5c277cf..6025411e 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContextTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancedRetryContextTest.java @@ -46,19 +46,19 @@ public class LoadBalancedRetryContextTest { } @AfterEach - public void tearDown() throws Exception { + public void tearDown() { this.context = null; this.request = null; } @Test - public void getRequest() throws Exception { + public void getRequest() { LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(this.context, this.request); then(lbContext.getRequest()).isEqualTo(this.request); } @Test - public void setRequest() throws Exception { + public void setRequest() { LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(this.context, this.request); HttpRequest newRequest = mock(HttpRequest.class); lbContext.setRequest(newRequest); @@ -66,7 +66,7 @@ public class LoadBalancedRetryContextTest { } @Test - public void getServiceInstance() throws Exception { + public void getServiceInstance() { LoadBalancedRetryContext lbContext = new LoadBalancedRetryContext(this.context, this.request); ServiceInstance serviceInstance = mock(ServiceInstance.class); lbContext.setServiceInstance(serviceInstance); diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryConfigurationTests.java index 08e5edc3..9f736755 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryConfigurationTests.java @@ -60,12 +60,10 @@ public class LoadBalancerRequestFactoryConfigurationTests { @Mock private ServiceInstance instance; - private byte[] body = new byte[] {}; + private final byte[] body = new byte[] {}; private ArgumentCaptor httpRequestCaptor; - private LoadBalancerRequestFactory lbReqFactory; - private LoadBalancerRequest lbRequest; @BeforeEach @@ -78,8 +76,8 @@ public class LoadBalancerRequestFactoryConfigurationTests { .properties("spring.aop.proxyTargetClass=true").sources(config, LoadBalancerAutoConfiguration.class) .run(); - this.lbReqFactory = context.getBean(LoadBalancerRequestFactory.class); - this.lbRequest = this.lbReqFactory.createRequest(this.request, this.body, this.execution); + LoadBalancerRequestFactory lbReqFactory = context.getBean(LoadBalancerRequestFactory.class); + this.lbRequest = lbReqFactory.createRequest(this.request, this.body, this.execution); return context; } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryTests.java index e5aaaca5..18a79b16 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerRequestFactoryTests.java @@ -96,7 +96,7 @@ public class LoadBalancerRequestFactoryTests { @Test public void testOneTransformer() throws Exception { - List transformers = Arrays.asList(this.transformer1); + List transformers = List.of(this.transformer1); when(this.transformer1.transformRequest(any(ServiceRequestWrapper.class), eq(this.instance))) .thenReturn(this.transformedRequest1); diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerUriToolsTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerUriToolsTests.java index 78a16301..7a40ebcb 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerUriToolsTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/LoadBalancerUriToolsTests.java @@ -188,8 +188,6 @@ class TestServiceInstance implements ServiceInstance { private String scheme = "http"; - private String host = "test.example"; - private int port = 8080; private boolean secure; @@ -218,6 +216,7 @@ class TestServiceInstance implements ServiceInstance { @Override public String getHost() { + String host = "test.example"; return host; } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTests.java index 21df34bb..0b4da563 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/RetryLoadBalancerInterceptorTests.java @@ -23,6 +23,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -34,6 +35,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.quality.Strictness; import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; @@ -90,7 +92,7 @@ public class RetryLoadBalancerInterceptorTests { lbRequestFactory = mock(LoadBalancerRequestFactory.class); properties = new LoadBalancerProperties(); properties.getRetry().setRetryOnAllExceptions(true); - lbFactory = mock(ReactiveLoadBalancer.Factory.class, withSettings().lenient()); + lbFactory = mock(ReactiveLoadBalancer.Factory.class, withSettings().strictness(Strictness.LENIENT)); when(lbFactory.getProperties(any())).thenReturn(properties); } @@ -115,9 +117,7 @@ public class RetryLoadBalancerInterceptorTests { when(lbRequestFactory.createRequest(any(), any(), any())).thenReturn(mock(LoadBalancerRequest.class)); - Assertions.assertThrows(IOException.class, () -> { - interceptor.intercept(request, body, execution); - }); + Assertions.assertThrows(IOException.class, () -> interceptor.intercept(request, body, execution)); verify(lbRequestFactory).createRequest(request, body, execution); } @@ -130,9 +130,7 @@ public class RetryLoadBalancerInterceptorTests { loadBalancedRetryFactory, lbFactory); byte[] body = new byte[] {}; ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - Assertions.assertThrows(IllegalStateException.class, () -> { - interceptor.intercept(request, body, execution); - }); + Assertions.assertThrows(IllegalStateException.class, () -> interceptor.intercept(request, body, execution)); } @Test @@ -287,9 +285,7 @@ public class RetryLoadBalancerInterceptorTests { new MyLoadBalancedRetryFactory(policy), lbFactory); byte[] body = new byte[] {}; ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - Assertions.assertThrows(IOException.class, () -> { - interceptor.intercept(request, body, execution); - }); + Assertions.assertThrows(IOException.class, () -> interceptor.intercept(request, body, execution)); verify(lbRequestFactory).createRequest(request, body, execution); } @@ -369,9 +365,8 @@ public class RetryLoadBalancerInterceptorTests { new MyLoadBalancedRetryFactory(policy, backOffPolicy, new RetryListener[] { myRetryListener }), lbFactory); ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class); - Assertions.assertThrows(TerminatedRetryException.class, () -> { - interceptor.intercept(request, new byte[] {}, execution); - }); + Assertions.assertThrows(TerminatedRetryException.class, + () -> interceptor.intercept(request, new byte[] {}, execution)); } @Test @@ -445,22 +440,12 @@ public class RetryLoadBalancerInterceptorTests { @Override public BackOffPolicy createBackOffPolicy(String service) { - if (backOffPolicy == null) { - return new NoBackOffPolicy(); - } - else { - return backOffPolicy; - } + return Objects.requireNonNullElseGet(backOffPolicy, NoBackOffPolicy::new); } @Override public RetryListener[] createRetryListeners(String service) { - if (retryListeners == null) { - return new RetryListener[0]; - } - else { - return retryListeners; - } + return Objects.requireNonNullElseGet(retryListeners, () -> new RetryListener[0]); } } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/DiscoveryClientBasedReactiveLoadBalancer.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/DiscoveryClientBasedReactiveLoadBalancer.java index 36b3678c..b9d9fb94 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/DiscoveryClientBasedReactiveLoadBalancer.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/DiscoveryClientBasedReactiveLoadBalancer.java @@ -63,8 +63,7 @@ class DiscoveryClientBasedReactiveLoadBalancer implements ReactiveLoadBalancer> choose(Request request) { List instances = discoveryClient.getInstances(serviceId); - if (request.getContext() instanceof RetryableRequestContext) { - RetryableRequestContext context = (RetryableRequestContext) request.getContext(); + if (request.getContext() instanceof RetryableRequestContext context) { if (context.getPreviousServiceInstance() != null) { List instancesCopy = discoveryClient.getInstances(serviceId); instancesCopy.remove(context.getPreviousServiceInstance()); diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerClientRequestTransformerTest.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerClientRequestTransformerTest.java index 57a7e5d9..fa13613e 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerClientRequestTransformerTest.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/LoadBalancerClientRequestTransformerTest.java @@ -96,7 +96,7 @@ class LoadBalancerClientRequestTransformerTest { assertThat(headers.getFirst("X-InstanceId")).isEqualTo("testServiceId"); } - class Transformer1 implements LoadBalancerClientRequestTransformer { + static class Transformer1 implements LoadBalancerClientRequestTransformer { @Override public ClientRequest transformRequest(ClientRequest request, ServiceInstance instance) { @@ -105,7 +105,7 @@ class LoadBalancerClientRequestTransformerTest { } - class Transformer2 implements LoadBalancerClientRequestTransformer { + static class Transformer2 implements LoadBalancerClientRequestTransformer { @Override public ClientRequest transformRequest(ClientRequest request, ServiceInstance instance) { diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerClientAutoConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerClientAutoConfigurationTests.java index 1e2eebcd..bf932523 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerClientAutoConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerClientAutoConfigurationTests.java @@ -166,7 +166,7 @@ public class ReactorLoadBalancerClientAutoConfigurationTests { @Bean ReactiveLoadBalancer.Factory reactiveLoadBalancerFactory(LoadBalancerProperties properties) { - return new ReactiveLoadBalancer.Factory() { + return new ReactiveLoadBalancer.Factory<>() { @Override public ReactiveLoadBalancer getInstance(String serviceId) { return new TestReactiveLoadBalancer(); @@ -211,7 +211,7 @@ public class ReactorLoadBalancerClientAutoConfigurationTests { return new TestService(loadBalancedWebClientBuilder()); } - private final class TestService { + private static final class TestService { public final WebClient webClient; diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunctionTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunctionTests.java index 671de21d..45d4b655 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunctionTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/ReactorLoadBalancerExchangeFilterFunctionTests.java @@ -173,7 +173,7 @@ class ReactorLoadBalancerExchangeFilterFunctionTests { @Bean ReactiveLoadBalancer.Factory reactiveLoadBalancerFactory(DiscoveryClient discoveryClient, LoadBalancerProperties properties) { - return new ReactiveLoadBalancer.Factory() { + return new ReactiveLoadBalancer.Factory<>() { private final TestLoadBalancerLifecycle testLoadBalancerLifecycle = new TestLoadBalancerLifecycle(); diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunctionIntegrationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunctionIntegrationTests.java index baef4abd..ebff116a 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunctionIntegrationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/client/loadbalancer/reactive/RetryableLoadBalancerExchangeFilterFunctionIntegrationTests.java @@ -229,7 +229,7 @@ class RetryableLoadBalancerExchangeFilterFunctionIntegrationTests { @Bean ReactiveLoadBalancer.Factory reactiveLoadBalancerFactory(DiscoveryClient discoveryClient, LoadBalancerProperties properties) { - return new ReactiveLoadBalancer.Factory() { + return new ReactiveLoadBalancer.Factory<>() { private final TestLoadBalancerLifecycle testLoadBalancerLifecycle = new TestLoadBalancerLifecycle(); diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/ConfigDataMissingEnvironmentPostProcessorTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/ConfigDataMissingEnvironmentPostProcessorTests.java index 62c1a588..26e88bbe 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/ConfigDataMissingEnvironmentPostProcessorTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/ConfigDataMissingEnvironmentPostProcessorTests.java @@ -110,7 +110,8 @@ public class ConfigDataMissingEnvironmentPostProcessorTests { assertThat(output).doesNotContain("Error binding spring.config.import"); } - public class TestConfigDataMissingEnvironmentPostProcessor extends ConfigDataMissingEnvironmentPostProcessor { + static public class TestConfigDataMissingEnvironmentPostProcessor + extends ConfigDataMissingEnvironmentPostProcessor { @Override protected boolean shouldProcessEnvironment(Environment environment) { diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientConfigurationTests.java index 1a62d562..b6a07b69 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/CustomHttpClientConfigurationTests.java @@ -53,27 +53,27 @@ public class CustomHttpClientConfigurationTests { OkHttpClientConnectionPoolFactory okHttpClientConnectionPoolFactory; @Test - public void connManFactory() throws Exception { + public void connManFactory() { then(ApacheHttpClientConnectionManagerFactory.class.isInstance(this.connectionManagerFactory)).isTrue(); then(CustomApplication.MyApacheHttpClientConnectionManagerFactory.class .isInstance(this.connectionManagerFactory)).isTrue(); } @Test - public void apacheHttpClientFactory() throws Exception { + public void apacheHttpClientFactory() { then(ApacheHttpClientFactory.class.isInstance(this.httpClientFactory)).isTrue(); then(CustomApplication.MyApacheHttpClientFactory.class.isInstance(this.httpClientFactory)).isTrue(); } @Test - public void connectionPoolFactory() throws Exception { + public void connectionPoolFactory() { then(OkHttpClientConnectionPoolFactory.class.isInstance(this.okHttpClientConnectionPoolFactory)).isTrue(); then(CustomApplication.MyOkHttpConnectionPoolFactory.class.isInstance(this.okHttpClientConnectionPoolFactory)) .isTrue(); } @Test - public void okHttpClientFactory() throws Exception { + public void okHttpClientFactory() { then(OkHttpClientFactory.class.isInstance(this.okHttpClientFactory)).isTrue(); then(CustomApplication.MyOkHttpClientFactory.class.isInstance(this.okHttpClientFactory)).isTrue(); } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactoryTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactoryTests.java index 2147ca0f..f59eaf96 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactoryTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultApacheHttpClientFactoryTests.java @@ -38,7 +38,7 @@ import static org.mockito.Mockito.mock; public class DefaultApacheHttpClientFactoryTests { @Test - public void createClient() throws Exception { + public void createClient() { final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100).setConnectTimeout(200) .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); CloseableHttpClient httpClient = new DefaultApacheHttpClientFactory(HttpClientBuilder.create()).createBuilder() diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultHttpClientConfigurationTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultHttpClientConfigurationTests.java index 0327779f..aba80a8e 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultHttpClientConfigurationTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/httpclient/DefaultHttpClientConfigurationTests.java @@ -45,26 +45,26 @@ public class DefaultHttpClientConfigurationTests { OkHttpClientConnectionPoolFactory okHttpClientConnectionPoolFactory; @Test - public void connManFactory() throws Exception { + public void connManFactory() { then(ApacheHttpClientConnectionManagerFactory.class.isInstance(this.connectionManagerFactory)).isTrue(); then(DefaultApacheHttpClientConnectionManagerFactory.class.isInstance(this.connectionManagerFactory)).isTrue(); } @Test - public void apacheHttpClientFactory() throws Exception { + public void apacheHttpClientFactory() { then(ApacheHttpClientFactory.class.isInstance(this.httpClientFactory)).isTrue(); then(DefaultApacheHttpClientFactory.class.isInstance(this.httpClientFactory)).isTrue(); } @Test - public void connPoolFactory() throws Exception { + public void connPoolFactory() { then(OkHttpClientConnectionPoolFactory.class.isInstance(this.okHttpClientConnectionPoolFactory)).isTrue(); then(DefaultOkHttpClientConnectionPoolFactory.class.isInstance(this.okHttpClientConnectionPoolFactory)) .isTrue(); } @Test - public void setOkHttpClientFactory() throws Exception { + public void setOkHttpClientFactory() { then(OkHttpClientFactory.class.isInstance(this.okHttpClientFactory)).isTrue(); then(DefaultOkHttpClientFactory.class.isInstance(this.okHttpClientFactory)).isTrue(); } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/security/tokenrelay/ResourceServerTokenRelayTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/security/tokenrelay/ResourceServerTokenRelayTests.java index bf1efc52..77f68dc2 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/security/tokenrelay/ResourceServerTokenRelayTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/commons/security/tokenrelay/ResourceServerTokenRelayTests.java @@ -72,7 +72,7 @@ public class ResourceServerTokenRelayTests { AccessTokenContextRelay accessTokenContextRelay; @Test - public void tokenRelayJWT() throws Exception { + public void tokenRelayJWT() { mockServerToReceiveRelay.expect(requestTo("https://example.com/test")) .andExpect(header("authorization", AUTH_HEADER_TO_BE_RELAYED)) @@ -82,7 +82,7 @@ public class ResourceServerTokenRelayTests { ResponseEntity exchange = testRestTemplate.exchange("/token-relay", HttpMethod.GET, authorizationHeader, String.class); - assertThat(exchange.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value()); + assertThat(exchange.getStatusCode().value()).isEqualTo(HttpStatus.OK.value()); assertThat(exchange.getBody()).isEqualTo(TEST_RESPONSE); mockServerToReceiveRelay.verify(); @@ -92,7 +92,7 @@ public class ResourceServerTokenRelayTests { private HttpEntity createAuthorizationHeader() { HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", AUTH_HEADER_TO_BE_RELAYED); - return new HttpEntity("parameters", headers); + return new HttpEntity<>("parameters", headers); } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierTests.java index 52171cf4..865fa7e0 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/CompatibilityVerifierTests.java @@ -36,8 +36,7 @@ public class CompatibilityVerifierTests { @Test public void should_not_print_the_report_when_no_errors_were_found(CapturedOutput output) { - CompositeCompatibilityVerifier verifier = new CompositeCompatibilityVerifier( - new ArrayList()); + CompositeCompatibilityVerifier verifier = new CompositeCompatibilityVerifier(new ArrayList<>()); verifier.verifyDependencies(); @@ -47,18 +46,8 @@ public class CompatibilityVerifierTests { @Test public void should_print_the_report_when_errors_were_found() { List list = new ArrayList<>(); - list.add(new CompatibilityVerifier() { - @Override - public VerificationResult verify() { - return VerificationResult.notCompatible("Wrong Boot version", "Use Boot version 1.2"); - } - }); - list.add(new CompatibilityVerifier() { - @Override - public VerificationResult verify() { - return VerificationResult.notCompatible("Wrong JDK version", "Use JDK 25"); - } - }); + list.add(() -> VerificationResult.notCompatible("Wrong Boot version", "Use Boot version 1.2")); + list.add(() -> VerificationResult.notCompatible("Wrong JDK version", "Use JDK 25")); CompositeCompatibilityVerifier verifier = new CompositeCompatibilityVerifier(list); try { diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/KeyAndCert.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/KeyAndCert.java index 40c03ec4..b3fb81ca 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/KeyAndCert.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/KeyAndCert.java @@ -51,7 +51,7 @@ public class KeyAndCert { } public String subject() { - String dn = certificate.getSubjectDN().getName(); + String dn = certificate.getSubjectX500Principal().getName(); int index = dn.indexOf('='); return dn.substring(index + 1); } diff --git a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SSHContextFactoryTests.java b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SSHContextFactoryTests.java index 12ef299d..0732d399 100644 --- a/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SSHContextFactoryTests.java +++ b/spring-cloud-commons/src/test/java/org/springframework/cloud/configuration/SSHContextFactoryTests.java @@ -68,7 +68,7 @@ public class SSHContextFactoryTests { } private static File saveCert(KeyAndCert keyCert) throws Exception { - return saveKeyStore(keyCert.subject(), () -> keyCert.storeCert()); + return saveKeyStore(keyCert.subject(), keyCert::storeCert); } private static File saveKeyStore(String prefix, KeyStoreSupplier func) throws Exception { diff --git a/spring-cloud-context-integration-tests/src/test/java/org/springframework/cloud/context/integration/RefreshScopeIntegrationTests.java b/spring-cloud-context-integration-tests/src/test/java/org/springframework/cloud/context/integration/RefreshScopeIntegrationTests.java index be8bb6c0..57cc81f3 100644 --- a/spring-cloud-context-integration-tests/src/test/java/org/springframework/cloud/context/integration/RefreshScopeIntegrationTests.java +++ b/spring-cloud-context-integration-tests/src/test/java/org/springframework/cloud/context/integration/RefreshScopeIntegrationTests.java @@ -70,7 +70,7 @@ public class RefreshScopeIntegrationTests { @Test @DirtiesContext - public void testSimpleProperties() throws Exception { + public void testSimpleProperties() { then(this.service.getMessage()).isEqualTo("Hello scope!"); then(this.service instanceof Advised).isTrue(); // Change the dynamic property source... @@ -83,7 +83,7 @@ public class RefreshScopeIntegrationTests { @Test @DirtiesContext - public void testRefresh() throws Exception { + public void testRefresh() { then(this.service.getMessage()).isEqualTo("Hello scope!"); String id1 = this.service.toString(); // Change the dynamic property source... @@ -101,7 +101,7 @@ public class RefreshScopeIntegrationTests { @Test @DirtiesContext - public void testRefreshBean() throws Exception { + public void testRefreshBean() { then(this.service.getMessage()).isEqualTo("Hello scope!"); String id1 = this.service.toString(); // Change the dynamic property source... @@ -121,10 +121,8 @@ public class RefreshScopeIntegrationTests { // see gh-349 @Test @DirtiesContext - public void testCheckedException() throws Exception { - Assertions.assertThrows(ServiceException.class, () -> { - this.service.throwsException(); - }); + public void testCheckedException() { + Assertions.assertThrows(ServiceException.class, () -> this.service.throwsException()); } public interface Service { @@ -169,13 +167,13 @@ public class RefreshScopeIntegrationTests { } @Override - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() { logger.debug("Initializing message: " + this.message); initCount++; } @Override - public void destroy() throws Exception { + public void destroy() { logger.debug("Destroying message: " + this.message); destroyCount++; this.message = null; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapApplicationListener.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapApplicationListener.java index 76e2fba7..f0467605 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapApplicationListener.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapApplicationListener.java @@ -288,7 +288,7 @@ public class BootstrapApplicationListener implements ApplicationListener(application.getInitializers()); target.addAll(getOrderedBeansOfType(context, ApplicationContextInitializer.class)); @@ -315,13 +315,12 @@ public class BootstrapApplicationListener implements ApplicationListener> target = new ArrayList>( - initializers); + ArrayList> target = new ArrayList<>(initializers); application.setInitializers(target); } private List getOrderedBeansOfType(ListableBeanFactory context, Class type) { - List result = new ArrayList(); + List result = new ArrayList<>(); for (String name : context.getBeanNamesForType(type)) { result.add(context.getBean(name, type)); } @@ -375,8 +374,7 @@ public class BootstrapApplicationListener implements ApplicationListener removed = environment.getPropertySources().remove(DEFAULT_PROPERTIES); - if (removed instanceof ExtendedDefaultPropertySource) { - ExtendedDefaultPropertySource defaultProperties = (ExtendedDefaultPropertySource) removed; + if (removed instanceof ExtendedDefaultPropertySource defaultProperties) { environment.getPropertySources() .addLast(new MapPropertySource(DEFAULT_PROPERTIES, defaultProperties.getSource())); for (PropertySource source : defaultProperties.getPropertySources().getPropertySources()) { @@ -428,7 +426,7 @@ public class BootstrapApplicationListener implements ApplicationListener) propertySource.getSource(); } - return new LinkedHashMap(); + return new LinkedHashMap<>(); } public CompositePropertySource getPropertySources() { diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapConfigFileApplicationListener.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapConfigFileApplicationListener.java index b6744eee..9ab18217 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapConfigFileApplicationListener.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/BootstrapConfigFileApplicationListener.java @@ -135,10 +135,7 @@ public class BootstrapConfigFileApplicationListener private static final Set LOAD_FILTERED_PROPERTY; static { - Set filteredProperties = new HashSet<>(); - filteredProperties.add("spring.profiles.active"); - filteredProperties.add("spring.profiles.include"); - LOAD_FILTERED_PROPERTY = Collections.unmodifiableSet(filteredProperties); + LOAD_FILTERED_PROPERTY = Set.of("spring.profiles.active", "spring.profiles.include"); } /** diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/BootstrapPropertySource.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/BootstrapPropertySource.java index 3a0dae2c..e92c6a77 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/BootstrapPropertySource.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/BootstrapPropertySource.java @@ -47,8 +47,7 @@ public class BootstrapPropertySource extends EnumerablePropertySource { @Override public String[] getPropertyNames() { - Set names = new LinkedHashSet<>(); - names.addAll(Arrays.asList(this.delegate.getPropertyNames())); + Set names = new LinkedHashSet<>(Arrays.asList(this.delegate.getPropertyNames())); return StringUtils.toStringArray(names); } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapConfiguration.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapConfiguration.java index 4791cb6f..661f6047 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapConfiguration.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceBootstrapConfiguration.java @@ -98,8 +98,7 @@ public class PropertySourceBootstrapConfiguration } List> sourceList = new ArrayList<>(); for (PropertySource p : source) { - if (p instanceof EnumerablePropertySource) { - EnumerablePropertySource enumerable = (EnumerablePropertySource) p; + if (p instanceof EnumerablePropertySource enumerable) { sourceList.add(new BootstrapPropertySource<>(enumerable)); } else { @@ -153,7 +152,7 @@ public class PropertySourceBootstrapConfiguration rebinder.setEnvironment(environment); // We can't fire the event in the ApplicationContext here (too early), but we can // create our own listener and poke it (it doesn't need the key changes) - rebinder.onApplicationEvent(new EnvironmentChangeEvent(applicationContext, Collections.emptySet())); + rebinder.onApplicationEvent(new EnvironmentChangeEvent(applicationContext, Collections.emptySet())); } private void insertPropertySources(MutablePropertySources propertySources, List> composite) { diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceLocator.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceLocator.java index cbac1bd8..2e68699e 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceLocator.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/config/PropertySourceLocator.java @@ -17,7 +17,6 @@ package org.springframework.cloud.bootstrap.config; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -52,7 +51,7 @@ public interface PropertySourceLocator { if (propertySource == null) { return Collections.emptyList(); } - if (CompositePropertySource.class.isInstance(propertySource)) { + if (propertySource instanceof CompositePropertySource) { Collection> sources = ((CompositePropertySource) propertySource).getPropertySources(); List> filteredSources = new ArrayList<>(); for (PropertySource p : sources) { @@ -63,7 +62,7 @@ public interface PropertySourceLocator { return filteredSources; } else { - return Arrays.asList(propertySource); + return List.of(propertySource); } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/AbstractEnvironmentDecrypt.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/AbstractEnvironmentDecrypt.java index a9b6b379..76cbceba 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/AbstractEnvironmentDecrypt.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/AbstractEnvironmentDecrypt.java @@ -94,11 +94,10 @@ public abstract class AbstractEnvironmentDecrypt { } } - else if (source instanceof EnumerablePropertySource) { + else if (source instanceof EnumerablePropertySource enumerable) { Map otherCollectionProperties = new LinkedHashMap<>(); boolean sourceHasDecryptedCollection = false; - EnumerablePropertySource enumerable = (EnumerablePropertySource) source; for (String key : enumerable.getPropertyNames()) { Object property = source.getProperty(key); if (property != null) { diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializer.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializer.java index dc7de109..10251059 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializer.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/encrypt/EnvironmentDecryptApplicationInitializer.java @@ -113,8 +113,7 @@ public class EnvironmentDecryptApplicationInitializer extends AbstractEnvironmen private void insert(ApplicationContext applicationContext, PropertySource propertySource) { ApplicationContext parent = applicationContext; while (parent != null) { - if (parent.getEnvironment() instanceof ConfigurableEnvironment) { - ConfigurableEnvironment mutable = (ConfigurableEnvironment) parent.getEnvironment(); + if (parent.getEnvironment() instanceof ConfigurableEnvironment mutable) { insert(mutable.getPropertySources(), propertySource); } parent = parent.getParent(); diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/support/OriginTrackedCompositePropertySource.java b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/support/OriginTrackedCompositePropertySource.java index c4e3e0bb..a169a511 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/support/OriginTrackedCompositePropertySource.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/bootstrap/support/OriginTrackedCompositePropertySource.java @@ -35,8 +35,7 @@ public class OriginTrackedCompositePropertySource extends CompositePropertySourc @SuppressWarnings("unchecked") public Origin getOrigin(String name) { for (PropertySource propertySource : getPropertySources()) { - if (propertySource instanceof OriginLookup) { - OriginLookup lookup = (OriginLookup) propertySource; + if (propertySource instanceof OriginLookup lookup) { Origin origin = lookup.getOrigin(name); if (origin != null) { return origin; diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentManager.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentManager.java index f32db63f..5cbe4688 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentManager.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/environment/EnvironmentManager.java @@ -44,7 +44,7 @@ public class EnvironmentManager implements ApplicationEventPublisherAware { private static final String MANAGER_PROPERTY_SOURCE = "manager"; - private Map map = new LinkedHashMap(); + private Map map = new LinkedHashMap<>(); private ConfigurableEnvironment environment; @@ -67,7 +67,7 @@ public class EnvironmentManager implements ApplicationEventPublisherAware { @ManagedOperation public Map reset() { - Map result = new LinkedHashMap(this.map); + Map result = new LinkedHashMap<>(this.map); if (!this.map.isEmpty()) { this.map.clear(); publish(new EnvironmentChangeEvent(this.publisher, result.keySet())); diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesBeans.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesBeans.java index 35ffc8d6..84d9d843 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesBeans.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/properties/ConfigurationPropertiesBeans.java @@ -57,9 +57,7 @@ public class ConfigurationPropertiesBeans implements BeanPostProcessor, Applicat this.beanFactory = (ConfigurableListableBeanFactory) applicationContext.getAutowireCapableBeanFactory(); } if (applicationContext.getParent() != null && applicationContext.getParent() - .getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory) { - ConfigurableListableBeanFactory listable = (ConfigurableListableBeanFactory) applicationContext.getParent() - .getAutowireCapableBeanFactory(); + .getAutowireCapableBeanFactory() instanceof ConfigurableListableBeanFactory listable) { String[] names = listable.getBeanNamesForType(ConfigurationPropertiesBeans.class); if (names.length == 1) { this.parent = (ConfigurationPropertiesBeans) listable.getBean(names[0]); @@ -105,7 +103,7 @@ public class ConfigurationPropertiesBeans implements BeanPostProcessor, Applicat } public Set getBeanNames() { - return new HashSet(this.beans.keySet()); + return new HashSet<>(this.beans.keySet()); } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/refresh/ContextRefresher.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/refresh/ContextRefresher.java index e3f575d2..98149392 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/refresh/ContextRefresher.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/refresh/ContextRefresher.java @@ -134,7 +134,7 @@ public abstract class ContextRefresher { } private Map changes(Map before, Map after) { - Map result = new HashMap(); + Map result = new HashMap<>(); for (String key : before.keySet()) { if (!after.containsKey(key)) { result.put(key, null); @@ -162,8 +162,8 @@ public abstract class ContextRefresher { } private Map extract(MutablePropertySources propertySources) { - Map result = new HashMap(); - List> sources = new ArrayList>(); + Map result = new HashMap<>(); + List> sources = new ArrayList<>(); for (PropertySource source : propertySources) { sources.add(0, source); } @@ -178,7 +178,7 @@ public abstract class ContextRefresher { private void extract(PropertySource parent, Map result) { if (parent instanceof CompositePropertySource) { try { - List> sources = new ArrayList>(); + List> sources = new ArrayList<>(); for (PropertySource source : ((CompositePropertySource) parent).getPropertySources()) { sources.add(0, source); } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java index d0de5b51..a0463401 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/restart/RestartEndpoint.java @@ -190,7 +190,7 @@ public class RestartEndpoint implements ApplicationListener new PostProcessor()); + context.registerBean(PostProcessor.class, PostProcessor::new); } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/GenericScope.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/GenericScope.java index 5ac36134..b75a564f 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/GenericScope.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/GenericScope.java @@ -126,7 +126,7 @@ public class GenericScope @Override public void destroy() { - List errors = new ArrayList(); + List errors = new ArrayList<>(); Collection wrappers = this.cache.clear(); for (BeanLifecycleWrapper wrapper : wrappers) { try { @@ -243,8 +243,7 @@ public class GenericScope public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { for (String name : registry.getBeanDefinitionNames()) { BeanDefinition definition = registry.getBeanDefinition(name); - if (definition instanceof RootBeanDefinition) { - RootBeanDefinition root = (RootBeanDefinition) definition; + if (definition instanceof RootBeanDefinition root) { if (root.getDecoratedDefinition() != null && root.hasBeanClass() && root.getBeanClass() == ScopedProxyFactoryBean.class) { if (getName().equals(root.getDecoratedDefinition().getBeanDefinition().getScope())) { @@ -321,7 +320,7 @@ public class GenericScope public Collection clear() { Collection values = this.cache.clear(); - Collection wrappers = new LinkedHashSet(); + Collection wrappers = new LinkedHashSet<>(); for (Object object : values) { wrappers.add((BeanLifecycleWrapper) object); } @@ -448,8 +447,7 @@ public class GenericScope public void setBeanFactory(BeanFactory beanFactory) { super.setBeanFactory(beanFactory); Object proxy = getObject(); - if (proxy instanceof Advised) { - Advised advised = (Advised) proxy; + if (proxy instanceof Advised advised) { advised.addAdvice(0, this); } } @@ -479,8 +477,7 @@ public class GenericScope Lock lock = readWriteLock.readLock(); lock.lock(); try { - if (proxy instanceof Advised) { - Advised advised = (Advised) proxy; + if (proxy instanceof Advised advised) { ReflectionUtils.makeAccessible(method); return ReflectionUtils.invokeMethod(method, advised.getTargetSource().getTarget(), invocation.getArguments()); diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/StandardScopeCache.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/StandardScopeCache.java index 76321cda..43cdb049 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/StandardScopeCache.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/StandardScopeCache.java @@ -29,14 +29,14 @@ import java.util.concurrent.ConcurrentMap; */ public class StandardScopeCache implements ScopeCache { - private final ConcurrentMap cache = new ConcurrentHashMap(); + private final ConcurrentMap cache = new ConcurrentHashMap<>(); public Object remove(String name) { return this.cache.remove(name); } public Collection clear() { - Collection values = new ArrayList(this.cache.values()); + Collection values = new ArrayList<>(this.cache.values()); this.cache.clear(); return values; } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadLocalScopeCache.java b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadLocalScopeCache.java index 82da39e8..a4f6f024 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadLocalScopeCache.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/context/scope/thread/ThreadLocalScopeCache.java @@ -29,11 +29,7 @@ import org.springframework.cloud.context.scope.ScopeCache; */ public class ThreadLocalScopeCache implements ScopeCache { - private ThreadLocal> data = new ThreadLocal>() { - protected ConcurrentMap initialValue() { - return new ConcurrentHashMap(); - } - }; + private ThreadLocal> data = ThreadLocal.withInitial(ConcurrentHashMap::new); public Object remove(String name) { return this.data.get().remove(name); @@ -41,7 +37,7 @@ public class ThreadLocalScopeCache implements ScopeCache { public Collection clear() { ConcurrentMap map = this.data.get(); - Collection values = new ArrayList(map.values()); + Collection values = new ArrayList<>(map.values()); map.clear(); return values; } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/health/RefreshScopeHealthIndicator.java b/spring-cloud-context/src/main/java/org/springframework/cloud/health/RefreshScopeHealthIndicator.java index 1b3b60c3..abeea9de 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/health/RefreshScopeHealthIndicator.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/health/RefreshScopeHealthIndicator.java @@ -44,7 +44,7 @@ public class RefreshScopeHealthIndicator extends AbstractHealthIndicator { } @Override - protected void doHealthCheck(Builder builder) throws Exception { + protected void doHealthCheck(Builder builder) { RefreshScope refreshScope = this.scope.getIfAvailable(); if (refreshScope != null) { Map errors = new HashMap<>(refreshScope.getErrors()); diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/logging/LoggingRebinder.java b/spring-cloud-context/src/main/java/org/springframework/cloud/logging/LoggingRebinder.java index 6250a0bb..7a32686b 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/logging/LoggingRebinder.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/logging/LoggingRebinder.java @@ -67,7 +67,7 @@ public class LoggingRebinder implements ApplicationListener levels = Binder.get(environment).bind("logging.level", STRING_STRING_MAP) .orElseGet(Collections::emptyMap); for (Entry entry : levels.entrySet()) { - setLogLevel(system, environment, entry.getKey(), entry.getValue().toString()); + setLogLevel(system, environment, entry.getKey(), entry.getValue()); } } diff --git a/spring-cloud-context/src/main/java/org/springframework/cloud/util/random/CachedRandomPropertySource.java b/spring-cloud-context/src/main/java/org/springframework/cloud/util/random/CachedRandomPropertySource.java index 1ed305ed..a9003051 100644 --- a/spring-cloud-context/src/main/java/org/springframework/cloud/util/random/CachedRandomPropertySource.java +++ b/spring-cloud-context/src/main/java/org/springframework/cloud/util/random/CachedRandomPropertySource.java @@ -40,7 +40,7 @@ public class CachedRandomPropertySource extends PropertySource { CachedRandomPropertySource(PropertySource randomValuePropertySource, Map> cache) { super(NAME, randomValuePropertySource); - this.cache = cache; + CachedRandomPropertySource.cache = cache; } @Override diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingCustomPropertySourceIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingCustomPropertySourceIntegrationTests.java index 696c33f1..dc20fdeb 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingCustomPropertySourceIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/BootstrapOrderingCustomPropertySourceIntegrationTests.java @@ -66,8 +66,8 @@ public class BootstrapOrderingCustomPropertySourceIntegrationTests { // This is added to bootstrap context as a source in bootstrap.properties protected static class PropertySourceConfiguration implements PropertySourceLocator { - public static Map MAP = new HashMap(Collections.singletonMap( - "custom.foo", "{cipher}6154ca04d4bb6144d672c4e3d750b5147116dd381946d51fa44f8bc25dc256f4")); + public static Map MAP = new HashMap<>(Collections.singletonMap("custom.foo", + "{cipher}6154ca04d4bb6144d672c4e3d750b5147116dd381946d51fa44f8bc25dc256f4")); @Override public PropertySource locate(Environment environment) { diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestBootstrapConfiguration.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestBootstrapConfiguration.java index adb66060..3be1123d 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestBootstrapConfiguration.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/TestBootstrapConfiguration.java @@ -60,16 +60,10 @@ public class TestBootstrapConfiguration { @Bean public ApplicationContextInitializer customInitializer() { - return new ApplicationContextInitializer() { - - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - ConfigurableEnvironment environment = applicationContext.getEnvironment(); - environment.getPropertySources().addLast( - new MapPropertySource("customProperties", Collections.singletonMap("custom.foo", - environment.resolvePlaceholders("${spring.application.name:bar}")))); - } - + return applicationContext -> { + ConfigurableEnvironment environment = applicationContext.getEnvironment(); + environment.getPropertySources().addLast(new MapPropertySource("customProperties", Collections + .singletonMap("custom.foo", environment.resolvePlaceholders("${spring.application.name:bar}")))); }; } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapConfigurationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapConfigurationTests.java index 016dba39..8d4cde51 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapConfigurationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/config/BootstrapConfigurationTests.java @@ -33,7 +33,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.cloud.bootstrap.TestHigherPriorityBootstrapConfiguration; -import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.CompositePropertySource; @@ -108,12 +107,9 @@ public class BootstrapConfigurationTests { public void bootstrapPropertiesAvailableInInitializer() { this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE) .properties("spring.cloud.bootstrap.enabled=true").sources(BareConfiguration.class) - .initializers(new ApplicationContextInitializer() { - @Override - public void initialize(ConfigurableApplicationContext applicationContext) { - // This property is defined in bootstrap.properties - then(applicationContext.getEnvironment().getProperty("info.name")).isEqualTo("child"); - } + .initializers(applicationContext -> { + // This property is defined in bootstrap.properties + then(applicationContext.getEnvironment().getProperty("info.name")).isEqualTo("child"); }).run(); then(this.context.getEnvironment().getPropertySources() .contains(PropertySourceBootstrapConfiguration.BOOTSTRAP_PROPERTY_SOURCE_NAME + "-testBootstrap")) @@ -144,10 +140,9 @@ public class BootstrapConfigurationTests { @Test public void failsOnPropertySource() { System.setProperty("expected.fail", "true"); - Throwable throwable = Assertions.assertThrows(RuntimeException.class, () -> { - this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE) - .properties("spring.cloud.bootstrap.enabled=true").sources(BareConfiguration.class).run(); - }); + Throwable throwable = Assertions.assertThrows(RuntimeException.class, + () -> this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE) + .properties("spring.cloud.bootstrap.enabled=true").sources(BareConfiguration.class).run()); then(throwable.getMessage().equals("Planned")); } @@ -201,8 +196,8 @@ public class BootstrapConfigurationTests { PropertySourceConfiguration.MAP.put("spring.cloud.config.overrideNone", "true"); PropertySourceConfiguration.MAP.put("spring.cloud.config.allowOverride", "true"); ConfigurableEnvironment environment = new StandardEnvironment(); - environment.getPropertySources().addLast( - new MapPropertySource("last", Collections.singletonMap("bootstrap.foo", "splat"))); + environment.getPropertySources() + .addLast(new MapPropertySource("last", Collections.singletonMap("bootstrap.foo", "splat"))); this.context = new SpringApplicationBuilder().web(WebApplicationType.NONE) .properties("spring.cloud.bootstrap.enabled=true").environment(environment) .sources(BareConfiguration.class).run(); @@ -415,7 +410,7 @@ public class BootstrapConfigurationTests { // This is added to bootstrap context as a source in bootstrap.properties protected static class PropertySourceConfiguration implements PropertySourceLocator { - public static Map MAP = new HashMap( + public static Map MAP = new HashMap<>( Collections.singletonMap("bootstrap.foo", "bar")); private String name; @@ -456,9 +451,9 @@ public class BootstrapConfigurationTests { // This is added to bootstrap context as a source in bootstrap.properties protected static class CompositePropertySourceConfiguration implements PropertySourceLocator { - public static Map MAP1 = new HashMap(); + public static Map MAP1 = new HashMap<>(); - public static Map MAP2 = new HashMap(); + public static Map MAP2 = new HashMap<>(); public CompositePropertySourceConfiguration() { MAP1.put("list.foo[0]", "hello"); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptorFactoryTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptorFactoryTests.java index faa7c940..e6ef9d39 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptorFactoryTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/bootstrap/encrypt/EncryptorFactoryTests.java @@ -16,7 +16,7 @@ package org.springframework.cloud.bootstrap.encrypt; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -36,7 +36,7 @@ public class EncryptorFactoryTests { @Test public void testWithRsaPrivateKey() throws Exception { String key = StreamUtils.copyToString(new ClassPathResource("/example-test-rsa-private-key").getInputStream(), - Charset.forName("ASCII")); + StandardCharsets.US_ASCII); TextEncryptor encryptor = new EncryptorFactory().create(key); String toEncrypt = "sample text to encrypt"; @@ -47,11 +47,11 @@ public class EncryptorFactoryTests { @Test public void testWithInvalidRsaPrivateKey() { - String key = "-----BEGIN RSA PRIVATE KEY-----\n" - + "MIIEowIBAAKCAQEAwClFgrRa/PUHPIJr9gvIPL6g6Rjp/TVZmVNOf2fL96DYbkj5\n"; - Assertions.assertThrows(RuntimeException.class, () -> { - new EncryptorFactory().create(key); - }); + String key = """ + -----BEGIN RSA PRIVATE KEY----- + MIIEowIBAAKCAQEAwClFgrRa/PUHPIJr9gvIPL6g6Rjp/TVZmVNOf2fL96DYbkj5 + """; + Assertions.assertThrows(RuntimeException.class, () -> new EncryptorFactory().create(key)); } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerIntegrationTests.java index c387b403..63d31f25 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/environment/EnvironmentManagerIntegrationTests.java @@ -101,7 +101,7 @@ public class EnvironmentManagerIntegrationTests { @Test public void coreWebExtensionAvailable() throws Exception { - this.mvc.perform(get(BASE_PATH + "/env/" + UUID.randomUUID().toString())).andExpect(status().isNotFound()); + this.mvc.perform(get(BASE_PATH + "/env/" + UUID.randomUUID())).andExpect(status().isNotFound()); } @Test diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderIntegrationTests.java index 82dd040e..db869da6 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderIntegrationTests.java @@ -58,7 +58,7 @@ public class ConfigurationPropertiesRebinderIntegrationTests { @Test @DirtiesContext - public void testSimpleProperties() throws Exception { + public void testSimpleProperties() { then(this.properties.getMessage()).isEqualTo("Hello scope!"); then(this.properties.getCount()).isEqualTo(1); // Change the dynamic property source... @@ -70,7 +70,7 @@ public class ConfigurationPropertiesRebinderIntegrationTests { @Test @DirtiesContext - public void testRefreshInParent() throws Exception { + public void testRefreshInParent() { then(this.config.getName()).isEqualTo("parent"); // Change the dynamic property source... TestPropertyValues.of("config.name=foo").applyTo(this.environment); @@ -81,7 +81,7 @@ public class ConfigurationPropertiesRebinderIntegrationTests { @Test @DirtiesContext - public void testRefresh() throws Exception { + public void testRefresh() { then(this.properties.getCount()).isEqualTo(1); then(this.properties.getMessage()).isEqualTo("Hello scope!"); // Change the dynamic property source... @@ -94,7 +94,7 @@ public class ConfigurationPropertiesRebinderIntegrationTests { @Test @DirtiesContext - public void testRefreshByName() throws Exception { + public void testRefreshByName() { then(this.properties.getCount()).isEqualTo(1); then(this.properties.getMessage()).isEqualTo("Hello scope!"); // Change the dynamic property source... diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderLifecycleIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderLifecycleIntegrationTests.java index 1a898eba..d50ec101 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderLifecycleIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderLifecycleIntegrationTests.java @@ -51,7 +51,7 @@ public class ConfigurationPropertiesRebinderLifecycleIntegrationTests { @Test @DirtiesContext - public void testRefresh() throws Exception { + public void testRefresh() { then(this.properties.getCount()).isEqualTo(0); then(this.properties.getMessage()).isEqualTo("Hello scope!"); // Change the dynamic property source... diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderProxyIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderProxyIntegrationTests.java index b4322033..70f01c85 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderProxyIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderProxyIntegrationTests.java @@ -55,7 +55,7 @@ public class ConfigurationPropertiesRebinderProxyIntegrationTests { @Test @DirtiesContext - public void testAppendProperties() throws Exception { + public void testAppendProperties() { // This comes out as a String not Integer if the rebinder processes the proxy // instead of the target then(this.properties.getExpiry().get("one")).isEqualTo(new Integer(168)); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderRefreshScopeIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderRefreshScopeIntegrationTests.java index 6b7a918b..598d97df 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderRefreshScopeIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/properties/ConfigurationPropertiesRebinderRefreshScopeIntegrationTests.java @@ -54,7 +54,7 @@ public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests { @Test @DirtiesContext - public void testSimpleProperties() throws Exception { + public void testSimpleProperties() { then(this.properties.getMessage()).isEqualTo("Hello scope!"); // Change the dynamic property source... TestPropertyValues.of("message:Foo").applyTo(this.environment); @@ -65,7 +65,7 @@ public class ConfigurationPropertiesRebinderRefreshScopeIntegrationTests { @Test @DirtiesContext - public void testRefresh() throws Exception { + public void testRefresh() { then(this.properties.getCount()).isEqualTo(1); then(this.properties.getMessage()).isEqualTo("Hello scope!"); then(this.properties.getCount()).isEqualTo(1); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherIntegrationTests.java index 44053693..a77b0357 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/refresh/ContextRefresherIntegrationTests.java @@ -48,7 +48,7 @@ public class ContextRefresherIntegrationTests { @Test @DirtiesContext - public void testSimpleProperties() throws Exception { + public void testSimpleProperties() { then(this.properties.getMessage()).isEqualTo("Hello scope!"); // Change the dynamic property source... this.properties.setMessage("Foo"); @@ -58,7 +58,7 @@ public class ContextRefresherIntegrationTests { @Test @DirtiesContext - public void testRefreshBean() throws Exception { + public void testRefreshBean() { then(this.properties.getMessage()).isEqualTo("Hello scope!"); // Change the dynamic property source... this.properties.setMessage("Foo"); @@ -69,7 +69,7 @@ public class ContextRefresherIntegrationTests { @Test @DirtiesContext - public void testUpdateHikari() throws Exception { + public void testUpdateHikari() { then(this.properties.getMessage()).isEqualTo("Hello scope!"); TestPropertyValues.of("spring.datasource.hikari.read-only=true").applyTo(this.environment); // ...and then refresh, so the bean is re-initialized: diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/restart/RestartIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/restart/RestartIntegrationTests.java index 3e28fa14..5d154d9d 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/restart/RestartIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/restart/RestartIntegrationTests.java @@ -42,7 +42,7 @@ public class RestartIntegrationTests { } @Test - public void testRestartTwice() throws Exception { + public void testRestartTwice() { this.context = SpringApplication.run(TestConfiguration.class, "--management.endpoint.restart.enabled=true", "--server.port=0", "--spring.cloud.bootstrap.enabled=true", diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/ImportRefreshScopeIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/ImportRefreshScopeIntegrationTests.java index 2eee178f..4798aa5a 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/ImportRefreshScopeIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/ImportRefreshScopeIntegrationTests.java @@ -43,7 +43,7 @@ public class ImportRefreshScopeIntegrationTests { private ExampleService service; @Test - public void testSimpleProperties() throws Exception { + public void testSimpleProperties() { then(this.service.getMessage()).isEqualTo("Hello scope!"); then(this.beanFactory.getBeanDefinition(ScopedProxyUtils.getTargetBeanName("service")).getScope()) .isEqualTo("refresh"); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/MoreRefreshScopeIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/MoreRefreshScopeIntegrationTests.java index 2513cea5..ce9a757e 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/MoreRefreshScopeIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/MoreRefreshScopeIntegrationTests.java @@ -68,7 +68,7 @@ public class MoreRefreshScopeIntegrationTests { @Test @DirtiesContext - public void testSimpleProperties() throws Exception { + public void testSimpleProperties() { then(this.service.getMessage()).isEqualTo("Hello scope!"); then(this.service instanceof Advised).isTrue(); // Change the dynamic property source... @@ -81,7 +81,7 @@ public class MoreRefreshScopeIntegrationTests { @Test @DirtiesContext - public void testRefresh() throws Exception { + public void testRefresh() { then(this.service.getMessage()).isEqualTo("Hello scope!"); String id1 = this.service.toString(); // Change the dynamic property source... @@ -98,7 +98,7 @@ public class MoreRefreshScopeIntegrationTests { @Test @DirtiesContext - public void testRefreshFails() throws Exception { + public void testRefreshFails() { then(this.service.getMessage()).isEqualTo("Hello scope!"); // Change the dynamic property source... TestPropertyValues.of("message:Foo", "delay:foo").applyTo(this.environment); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConcurrencyTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConcurrencyTests.java index 06a96cc9..403f1c10 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConcurrencyTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConcurrencyTests.java @@ -16,7 +16,6 @@ package org.springframework.cloud.context.scope.refresh; -import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -72,17 +71,14 @@ public class RefreshScopeConcurrencyTests { this.properties.setMessage("Foo"); this.properties.setDelay(500); final CountDownLatch latch = new CountDownLatch(1); - Future result = this.executor.submit(new Callable() { - @Override - public String call() throws Exception { - logger.debug("Background started."); - try { - return RefreshScopeConcurrencyTests.this.service.getMessage(); - } - finally { - latch.countDown(); - logger.debug("Background done."); - } + Future result = this.executor.submit(() -> { + logger.debug("Background started."); + try { + return RefreshScopeConcurrencyTests.this.service.getMessage(); + } + finally { + latch.countDown(); + logger.debug("Background done."); } }); then(latch.await(15000, TimeUnit.MILLISECONDS)).isTrue(); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationScaleTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationScaleTests.java index 60eb2b20..ed9518ee 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationScaleTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationScaleTests.java @@ -18,7 +18,6 @@ package org.springframework.cloud.context.scope.refresh; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -81,25 +80,19 @@ public class RefreshScopeConfigurationScaleTests { final CountDownLatch latch = new CountDownLatch(n); List> results = new ArrayList<>(); for (int i = 0; i < n; i++) { - results.add(this.executor.submit(new Callable() { - @Override - public String call() throws Exception { - logger.debug("Background started."); - try { - return RefreshScopeConfigurationScaleTests.this.service.getMessage(); - } - finally { - latch.countDown(); - logger.debug("Background done."); - } + results.add(this.executor.submit(() -> { + logger.debug("Background started."); + try { + return RefreshScopeConfigurationScaleTests.this.service.getMessage(); + } + finally { + latch.countDown(); + logger.debug("Background done."); } })); - this.executor.submit(new Runnable() { - @Override - public void run() { - logger.debug("Refreshing."); - RefreshScopeConfigurationScaleTests.this.scope.refreshAll(); - } + this.executor.submit(() -> { + logger.debug("Refreshing."); + RefreshScopeConfigurationScaleTests.this.scope.refreshAll(); }); } then(latch.await(15000, TimeUnit.MILLISECONDS)).isTrue(); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationTests.java index e2c8a868..10dbf51e 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeConfigurationTests.java @@ -63,7 +63,7 @@ public class RefreshScopeConfigurationTests { * See gh-43 */ @Test - public void configurationWithRefreshScope() throws Exception { + public void configurationWithRefreshScope() { this.context = new AnnotationConfigApplicationContext(Application.class, PropertyPlaceholderAutoConfiguration.class, RefreshAutoConfiguration.class, LifecycleMvcEndpointAutoConfiguration.class); @@ -77,7 +77,7 @@ public class RefreshScopeConfigurationTests { } @Test - public void refreshScopeOnBean() throws Exception { + public void refreshScopeOnBean() { this.context = new AnnotationConfigApplicationContext(ClientApp.class, PropertyPlaceholderAutoConfiguration.class, RefreshAutoConfiguration.class, LifecycleMvcEndpointAutoConfiguration.class); @@ -89,7 +89,7 @@ public class RefreshScopeConfigurationTests { } @Test - public void refreshScopeOnNested() throws Exception { + public void refreshScopeOnNested() { this.context = new AnnotationConfigApplicationContext(NestedApp.class, PropertyPlaceholderAutoConfiguration.class, RefreshAutoConfiguration.class, LifecycleMvcEndpointAutoConfiguration.class); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeIntegrationTests.java index aecd8518..2516b1d7 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeIntegrationTests.java @@ -68,7 +68,7 @@ public class RefreshScopeIntegrationTests { @Test @DirtiesContext - public void testSimpleProperties() throws Exception { + public void testSimpleProperties() { then(this.service.getMessage()).isEqualTo("Hello scope!"); then(this.service instanceof Advised).isTrue(); // Change the dynamic property source... @@ -81,7 +81,7 @@ public class RefreshScopeIntegrationTests { @Test @DirtiesContext - public void testRefresh() throws Exception { + public void testRefresh() { then(this.service.getMessage()).isEqualTo("Hello scope!"); String id1 = this.service.toString(); // Change the dynamic property source... @@ -99,7 +99,7 @@ public class RefreshScopeIntegrationTests { @Test @DirtiesContext - public void testRefreshBean() throws Exception { + public void testRefreshBean() { then(this.service.getMessage()).isEqualTo("Hello scope!"); String id1 = this.service.toString(); // Change the dynamic property source... @@ -120,9 +120,7 @@ public class RefreshScopeIntegrationTests { @Test @DirtiesContext public void testCheckedException() { - Assertions.assertThrows(ServiceException.class, () -> { - this.service.throwsException(); - }); + Assertions.assertThrows(ServiceException.class, () -> this.service.throwsException()); } public interface Service { diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeLazyIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeLazyIntegrationTests.java index c0aee999..18414835 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeLazyIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeLazyIntegrationTests.java @@ -70,7 +70,7 @@ public class RefreshScopeLazyIntegrationTests { @Test @DirtiesContext - public void testSimpleProperties() throws Exception { + public void testSimpleProperties() { then(this.service.getMessage()).isEqualTo("Hello scope!"); then(this.service instanceof Advised).isTrue(); // Change the dynamic property source... @@ -83,7 +83,7 @@ public class RefreshScopeLazyIntegrationTests { @Test @DirtiesContext - public void testRefresh() throws Exception { + public void testRefresh() { then(this.service.getMessage()).isEqualTo("Hello scope!"); String id1 = this.service.toString(); // Change the dynamic property source... @@ -101,7 +101,7 @@ public class RefreshScopeLazyIntegrationTests { @Test @DirtiesContext - public void testRefreshBean() throws Exception { + public void testRefreshBean() { then(this.service.getMessage()).isEqualTo("Hello scope!"); String id1 = this.service.toString(); // Change the dynamic property source... diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeListBindingIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeListBindingIntegrationTests.java index 2831adac..9e54a336 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeListBindingIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeListBindingIntegrationTests.java @@ -56,7 +56,7 @@ public class RefreshScopeListBindingIntegrationTests { @Test @DirtiesContext - public void testAppendProperties() throws Exception { + public void testAppendProperties() { then("[one, two]").isEqualTo(this.properties.getMessages().toString()); then(this.properties instanceof Advised).isTrue(); TestPropertyValues.of("test.messages[0]:foo").applyTo(this.environment); @@ -66,7 +66,7 @@ public class RefreshScopeListBindingIntegrationTests { @Test @DirtiesContext - public void testReplaceProperties() throws Exception { + public void testReplaceProperties() { then("[one, two]").isEqualTo(this.properties.getMessages().toString()); then(this.properties instanceof Advised).isTrue(); Map map = findTestProperties(); @@ -104,7 +104,7 @@ public class RefreshScopeListBindingIntegrationTests { @ManagedResource protected static class TestProperties { - private List messages = new ArrayList(); + private List messages = new ArrayList<>(); public List getMessages() { return this.messages; diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopePureScaleTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopePureScaleTests.java index 61cc3da7..15a0efe2 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopePureScaleTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopePureScaleTests.java @@ -18,7 +18,6 @@ package org.springframework.cloud.context.scope.refresh; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -72,25 +71,19 @@ public class RefreshScopePureScaleTests { final CountDownLatch latch = new CountDownLatch(n); List> results = new ArrayList<>(); for (int i = 0; i < n; i++) { - results.add(this.executor.submit(new Callable() { - @Override - public String call() throws Exception { - logger.debug("Background started."); - try { - return RefreshScopePureScaleTests.this.service.getMessage(); - } - finally { - latch.countDown(); - logger.debug("Background done."); - } + results.add(this.executor.submit(() -> { + logger.debug("Background started."); + try { + return RefreshScopePureScaleTests.this.service.getMessage(); + } + finally { + latch.countDown(); + logger.debug("Background done."); } })); - this.executor.submit(new Runnable() { - @Override - public void run() { - logger.debug("Refreshing."); - RefreshScopePureScaleTests.this.scope.refreshAll(); - } + this.executor.submit(() -> { + logger.debug("Refreshing."); + RefreshScopePureScaleTests.this.scope.refreshAll(); }); } then(latch.await(15000, TimeUnit.MILLISECONDS)).isTrue(); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeScaleTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeScaleTests.java index 056c9065..7582604a 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeScaleTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeScaleTests.java @@ -16,7 +16,6 @@ package org.springframework.cloud.context.scope.refresh; -import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -77,17 +76,14 @@ public class RefreshScopeScaleTests { final CountDownLatch latch = new CountDownLatch(n); Future result = null; for (int i = 0; i < n; i++) { - result = this.executor.submit(new Callable() { - @Override - public String call() throws Exception { - logger.debug("Background started."); - try { - return RefreshScopeScaleTests.this.service.getMessage(); - } - finally { - latch.countDown(); - logger.debug("Background done."); - } + result = this.executor.submit(() -> { + logger.debug("Background started."); + try { + return RefreshScopeScaleTests.this.service.getMessage(); + } + finally { + latch.countDown(); + logger.debug("Background done."); } }); } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeSerializationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeSerializationTests.java index 88f7e896..1fda3f19 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeSerializationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeSerializationTests.java @@ -33,14 +33,14 @@ import static org.assertj.core.api.BDDAssertions.then; public class RefreshScopeSerializationTests { @Test - public void defaultApplicationContextId() throws Exception { + public void defaultApplicationContextId() { ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfiguration.class) .properties("spring.cloud.bootstrap.enabled=true").web(WebApplicationType.NONE).run(); then(context.getId()).isEqualTo("application-1"); } @Test - public void serializationIdReproducible() throws Exception { + public void serializationIdReproducible() { String first = getBeanFactory().getSerializationId(); String second = getBeanFactory().getSerializationId(); then(first).isNotNull(); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeWebIntegrationTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeWebIntegrationTests.java index 748e936a..1d2a7a28 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeWebIntegrationTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/context/scope/refresh/RefreshScopeWebIntegrationTests.java @@ -55,13 +55,13 @@ public class RefreshScopeWebIntegrationTests { private ConfigurableListableBeanFactory beanFactory; @Test - public void scopeOnBeanDefinition() throws Exception { + public void scopeOnBeanDefinition() { then(this.beanFactory.getBeanDefinition(ScopedProxyUtils.getTargetBeanName("application")).getScope()) .isEqualTo("refresh"); } @Test - public void beanAccess() throws Exception { + public void beanAccess() { this.application.hello(); this.environmentManager.setProperty("message", "Hello Dave!"); this.scope.refreshAll(); diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/endpoint/RefreshEndpointTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/endpoint/RefreshEndpointTests.java index 05db3418..ac4138bb 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/endpoint/RefreshEndpointTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/endpoint/RefreshEndpointTests.java @@ -70,7 +70,7 @@ public class RefreshEndpointTests { @Test @Disabled // FIXME: legacy - public void keysComputedWhenAdded() throws Exception { + public void keysComputedWhenAdded() { this.context = new SpringApplicationBuilder(Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF) .properties("spring.cloud.bootstrap.enabled=true", "spring.cloud.bootstrap.name:none").run(); RefreshScope scope = new RefreshScope(); @@ -84,7 +84,7 @@ public class RefreshEndpointTests { @Test @Disabled // FIXME: legacy - public void keysComputedWhenOveridden() throws Exception { + public void keysComputedWhenOveridden() { this.context = new SpringApplicationBuilder(Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF) .properties("spring.cloud.bootstrap.enabled=true", "spring.cloud.bootstrap.name:none").run(); RefreshScope scope = new RefreshScope(); @@ -97,7 +97,7 @@ public class RefreshEndpointTests { } @Test - public void keysComputedWhenChangesInExternalProperties() throws Exception { + public void keysComputedWhenChangesInExternalProperties() { this.context = new SpringApplicationBuilder(Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF) .properties("spring.cloud.bootstrap.name:none", "spring.cloud.bootstrap.enabled=true").run(); RefreshScope scope = new RefreshScope(); @@ -111,7 +111,7 @@ public class RefreshEndpointTests { } @Test - public void springMainSourcesEmptyInRefreshCycle() throws Exception { + public void springMainSourcesEmptyInRefreshCycle() { this.context = new SpringApplicationBuilder(Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF) .properties("spring.cloud.bootstrap.name:none").run(); RefreshScope scope = new RefreshScope(); @@ -128,7 +128,7 @@ public class RefreshEndpointTests { } @Test - public void eventsPublishedInOrder() throws Exception { + public void eventsPublishedInOrder() { this.context = new SpringApplicationBuilder(Empty.class).web(WebApplicationType.NONE).bannerMode(Mode.OFF) .run(); RefreshScope scope = new RefreshScope(); @@ -170,7 +170,7 @@ public class RefreshEndpointTests { @Configuration(proxyBeanMethods = false) protected static class Empty implements SmartApplicationListener { - private List events = new ArrayList(); + private List events = new ArrayList<>(); @Override public boolean supportsEventType(Class eventType) { @@ -192,8 +192,7 @@ public class RefreshEndpointTests { @Override public PropertySource locate(Environment environment) { - return new MapPropertySource("external", - Collections.singletonMap("external.message", "I'm External")); + return new MapPropertySource("external", Collections.singletonMap("external.message", "I'm External")); } } diff --git a/spring-cloud-context/src/test/java/org/springframework/cloud/util/random/CachedRandomPropertySourceTests.java b/spring-cloud-context/src/test/java/org/springframework/cloud/util/random/CachedRandomPropertySourceTests.java index c0349225..f39f93d5 100644 --- a/spring-cloud-context/src/test/java/org/springframework/cloud/util/random/CachedRandomPropertySourceTests.java +++ b/spring-cloud-context/src/test/java/org/springframework/cloud/util/random/CachedRandomPropertySourceTests.java @@ -74,7 +74,7 @@ public class CachedRandomPropertySourceTests { private HashMap> createCache(HashMap keyCount, HashMap, String> typeToKeyLookup, HashMap typeCount) { - return new HashMap>() { + return new HashMap<>() { @Override public Map computeIfAbsent(String key, Function> mappingFunction) { @@ -96,7 +96,7 @@ public class CachedRandomPropertySourceTests { private HashMap createTypeCache(HashMap, String> typeToKeyLookup, HashMap typeCount) { - return new HashMap() { + return new HashMap<>() { @Override public Object computeIfAbsent(String key, Function mappingFunction) { if (!containsKey(key)) { diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientSpecification.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientSpecification.java index 81a5b5f7..e4f9b6a4 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientSpecification.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/annotation/LoadBalancerClientSpecification.java @@ -82,7 +82,7 @@ public class LoadBalancerClientSpecification implements NamedContextFactory.Spec @Override public int hashCode() { - return Objects.hash(this.name, this.configuration); + return Objects.hash(this.name, Arrays.hashCode(this.configuration)); } } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/cache/CaffeineBasedLoadBalancerCacheManager.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/cache/CaffeineBasedLoadBalancerCacheManager.java index 6cd85188..67a0269f 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/cache/CaffeineBasedLoadBalancerCacheManager.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/cache/CaffeineBasedLoadBalancerCacheManager.java @@ -37,7 +37,7 @@ public class CaffeineBasedLoadBalancerCacheManager extends CaffeineCacheManager public CaffeineBasedLoadBalancerCacheManager(String cacheName, LoadBalancerCacheProperties properties) { super(cacheName); - if (!StringUtils.isEmpty(properties.getCaffeine().getSpec())) { + if (StringUtils.hasText(properties.getCaffeine().getSpec())) { setCacheSpecification(properties.getCaffeine().getSpec()); } else { diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/HealthCheckServiceInstanceListSupplier.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/HealthCheckServiceInstanceListSupplier.java index 18792431..c1e83287 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/HealthCheckServiceInstanceListSupplier.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/HealthCheckServiceInstanceListSupplier.java @@ -17,7 +17,6 @@ package org.springframework.cloud.loadbalancer.core; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.function.BiFunction; @@ -77,8 +76,7 @@ public class HealthCheckServiceInstanceListSupplier extends DelegatingServiceIns .onlyIf(repeatContext -> this.healthCheck.getRefetchInstances()) .fixedBackoff(healthCheck.getRefetchInstancesInterval()); Flux> aliveInstancesFlux = Flux.defer(delegate).repeatWhen(aliveInstancesReplayRepeat) - .switchMap(serviceInstances -> healthCheckFlux(serviceInstances) - .map(alive -> Collections.unmodifiableList(new ArrayList<>(alive)))); + .switchMap(serviceInstances -> healthCheckFlux(serviceInstances).map(alive -> List.copyOf(alive))); aliveInstancesReplay = aliveInstancesFlux.delaySubscription(healthCheck.getInitialDelay()).replay(1) .refCount(1); } @@ -94,8 +92,7 @@ public class HealthCheckServiceInstanceListSupplier extends DelegatingServiceIns .onlyIf(repeatContext -> this.healthCheck.getRefetchInstances()) .fixedBackoff(healthCheck.getRefetchInstancesInterval()); Flux> aliveInstancesFlux = Flux.defer(delegate).repeatWhen(aliveInstancesReplayRepeat) - .switchMap(serviceInstances -> healthCheckFlux(serviceInstances) - .map(alive -> Collections.unmodifiableList(new ArrayList<>(alive)))); + .switchMap(serviceInstances -> healthCheckFlux(serviceInstances).map(alive -> List.copyOf(alive))); aliveInstancesReplay = aliveInstancesFlux.delaySubscription(healthCheck.getInitialDelay()).replay(1) .refCount(1); } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RequestBasedStickySessionServiceInstanceListSupplier.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RequestBasedStickySessionServiceInstanceListSupplier.java index 4bf2bf81..c46009c5 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RequestBasedStickySessionServiceInstanceListSupplier.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RequestBasedStickySessionServiceInstanceListSupplier.java @@ -94,8 +94,8 @@ public class RequestBasedStickySessionServiceInstanceListSupplier extends Delega for (ServiceInstance serviceInstance : serviceInstances) { if (cookie.equals(serviceInstance.getInstanceId())) { if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Returning the service instance: %s. Found for cookie: %s", - serviceInstance.toString(), cookie)); + LOG.debug(String.format("Returning the service instance: %s. Found for cookie: %s", serviceInstance, + cookie)); } return Collections.singletonList(serviceInstance); } diff --git a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RetryAwareServiceInstanceListSupplier.java b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RetryAwareServiceInstanceListSupplier.java index 60c49802..9991ebfe 100644 --- a/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RetryAwareServiceInstanceListSupplier.java +++ b/spring-cloud-loadbalancer/src/main/java/org/springframework/cloud/loadbalancer/core/RetryAwareServiceInstanceListSupplier.java @@ -49,10 +49,9 @@ public class RetryAwareServiceInstanceListSupplier extends DelegatingServiceInst @Override public Flux> get(Request request) { - if (!(request.getContext() instanceof RetryableRequestContext)) { + if (!(request.getContext() instanceof RetryableRequestContext context)) { return delegate.get(request); } - RetryableRequestContext context = (RetryableRequestContext) request.getContext(); ServiceInstance previousServiceInstance = context.getPreviousServiceInstance(); if (previousServiceInstance == null) { return delegate.get(request); diff --git a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/config/BlockingLoadBalancerClientAutoConfigurationTests.java b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/config/BlockingLoadBalancerClientAutoConfigurationTests.java index c2d2ea3f..9646f2dc 100644 --- a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/config/BlockingLoadBalancerClientAutoConfigurationTests.java +++ b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/config/BlockingLoadBalancerClientAutoConfigurationTests.java @@ -48,9 +48,8 @@ class BlockingLoadBalancerClientAutoConfigurationTests { @Test public void worksWithoutSpringWeb() { - applicationContextRunner.withClassLoader(new FilteredClassLoader(RestTemplate.class)).run(context -> { - assertThat(context).doesNotHaveBean(BlockingLoadBalancerClient.class); - }); + applicationContextRunner.withClassLoader(new FilteredClassLoader(RestTemplate.class)) + .run(context -> assertThat(context).doesNotHaveBean(BlockingLoadBalancerClient.class)); } } diff --git a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/DiscoveryClientServiceInstanceListSupplierTests.java b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/DiscoveryClientServiceInstanceListSupplierTests.java index 6ff526be..6fb2287c 100644 --- a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/DiscoveryClientServiceInstanceListSupplierTests.java +++ b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/DiscoveryClientServiceInstanceListSupplierTests.java @@ -17,6 +17,7 @@ package org.springframework.cloud.loadbalancer.core; import java.time.Duration; +import java.util.Collections; import org.assertj.core.util.Lists; import org.junit.jupiter.api.BeforeEach; @@ -104,7 +105,7 @@ class DiscoveryClientServiceInstanceListSupplierTests { StepVerifier.withVirtualTime(() -> { supplier = new DiscoveryClientServiceInstanceListSupplier(reactiveDiscoveryClient, environment); return supplier.get(); - }).expectSubscription().expectNext(Lists.emptyList()).thenCancel().verify(VERIFICATION_TIMEOUT); + }).expectSubscription().expectNext(Collections.emptyList()).thenCancel().verify(VERIFICATION_TIMEOUT); } @Test @@ -112,7 +113,7 @@ class DiscoveryClientServiceInstanceListSupplierTests { environment.setProperty(SERVICE_DISCOVERY_TIMEOUT, "100ms"); when(reactiveDiscoveryClient.getInstances(SERVICE_ID)).thenReturn(Flux.never()); StepVerifier.create(new DiscoveryClientServiceInstanceListSupplier(reactiveDiscoveryClient, environment).get()) - .expectSubscription().expectNext(Lists.emptyList()).thenCancel().verify(VERIFICATION_TIMEOUT); + .expectSubscription().expectNext(Collections.emptyList()).thenCancel().verify(VERIFICATION_TIMEOUT); } @Test @@ -151,7 +152,7 @@ class DiscoveryClientServiceInstanceListSupplierTests { StepVerifier.withVirtualTime(() -> { supplier = new DiscoveryClientServiceInstanceListSupplier(discoveryClient, environment); return supplier.get(); - }).expectSubscription().expectNext(Lists.emptyList()).thenCancel().verify(VERIFICATION_TIMEOUT); + }).expectSubscription().expectNext(Collections.emptyList()).thenCancel().verify(VERIFICATION_TIMEOUT); } @Test @@ -161,7 +162,7 @@ class DiscoveryClientServiceInstanceListSupplierTests { when(discoveryClient.getInstances(SERVICE_ID)).thenAnswer(new AnswersWithDelay(200, new Returns( Lists.list(instance("1host", false), instance("2host-secure", true), instance("3host", false))))); StepVerifier.create(new DiscoveryClientServiceInstanceListSupplier(discoveryClient, environment).get()) - .expectSubscription().expectNext(Lists.emptyList()).thenCancel().verify(VERIFICATION_TIMEOUT); + .expectSubscription().expectNext(Collections.emptyList()).thenCancel().verify(VERIFICATION_TIMEOUT); } } diff --git a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/LoadBalancerTests.java b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/LoadBalancerTests.java index df648106..08a3007b 100644 --- a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/LoadBalancerTests.java +++ b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/core/LoadBalancerTests.java @@ -165,8 +165,7 @@ class LoadBalancerTests { @SuppressWarnings("rawtypes") @Override public Mono> choose(Request request) { - if (request.getContext() instanceof DefaultRequestContext) { - DefaultRequestContext requestContext = (DefaultRequestContext) request.getContext(); + if (request.getContext() instanceof DefaultRequestContext requestContext) { return Mono.just(new DefaultResponse(instance(requestContext.getHint(), "host", false))); } return Mono.empty(); diff --git a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/security/OAuth2LoadBalancerClientAutoConfigurationTests.java b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/security/OAuth2LoadBalancerClientAutoConfigurationTests.java index 3771a9af..5490f8f2 100644 --- a/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/security/OAuth2LoadBalancerClientAutoConfigurationTests.java +++ b/spring-cloud-loadbalancer/src/test/java/org/springframework/cloud/loadbalancer/security/OAuth2LoadBalancerClientAutoConfigurationTests.java @@ -74,7 +74,7 @@ public class OAuth2LoadBalancerClientAutoConfigurationTests { @Test @Ignore - public void userInfoLoadBalancedNoRetry() throws Exception { + public void userInfoLoadBalancedNoRetry() { this.context = new SpringApplicationBuilder(ClientConfiguration.class).properties("spring.config.name=test", "server.port=0", "security.oauth2.resource.userInfoUri:https://nosuchservice", "spring.cloud.oauth2.load-balanced.enabled=true").run(); diff --git a/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ModifiedClassPathRunner.java b/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ModifiedClassPathRunner.java index 3858b3fc..8d712637 100644 --- a/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ModifiedClassPathRunner.java +++ b/spring-cloud-test-support/src/main/java/org/springframework/cloud/test/ModifiedClassPathRunner.java @@ -90,8 +90,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { @Override protected Object createTest() throws Exception { ModifiedClassPathTestClass testClass = (ModifiedClassPathTestClass) getTestClass(); - return testClass - .doWithModifiedClassPathThreadContextClassLoader(() -> ModifiedClassPathRunner.super.createTest()); + return testClass.doWithModifiedClassPathThreadContextClassLoader(ModifiedClassPathRunner.super::createTest); } private URLClassLoader createTestClassLoader(Class testClass) throws Exception { @@ -113,7 +112,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { return extractedUrls.toArray(new URL[0]); } - private Stream doExtractUrls(ClassLoader classLoader) throws Exception { + private Stream doExtractUrls(ClassLoader classLoader) { if (classLoader instanceof URLClassLoader) { return Stream.of(((URLClassLoader) classLoader).getURLs()); } @@ -180,9 +179,8 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private URL[] processUrls(URL[] urls, Class testClass) throws Exception { MergedAnnotations annotations = MergedAnnotations.from(testClass, SearchStrategy.TYPE_HIERARCHY); ClassPathEntryFilter filter = new ClassPathEntryFilter(annotations.get(ClassPathExclusions.class)); - List processedUrls = new ArrayList<>(); List additionalUrls = getAdditionalUrls(annotations.get(ClassPathOverrides.class)); - processedUrls.addAll(additionalUrls); + List processedUrls = new ArrayList<>(additionalUrls); for (URL url : urls) { if (!filter.isExcluded(url)) { processedUrls.add(url); @@ -206,7 +204,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession(); LocalRepository localRepository = new LocalRepository(System.getProperty("user.home") + "/.m2/repository"); session.setLocalRepositoryManager(repositorySystem.newLocalRepositoryManager(session, localRepository)); - CollectRequest collectRequest = new CollectRequest(null, Arrays.asList( + CollectRequest collectRequest = new CollectRequest(null, Collections.singletonList( new RemoteRepository.Builder("central", "default", "https://repo.maven.apache.org/maven2").build())); collectRequest.setDependencies(createDependencies(coordinates)); @@ -236,7 +234,7 @@ public class ModifiedClassPathRunner extends BlockJUnit4ClassRunner { private final AntPathMatcher matcher = new AntPathMatcher(); - private ClassPathEntryFilter(MergedAnnotation annotation) throws Exception { + private ClassPathEntryFilter(MergedAnnotation annotation) { this.exclusions = new ArrayList<>(); this.exclusions.add("log4j-*.jar"); if (annotation.isPresent()) {